如何重新执行任务,以便多次调用Task.Start()?
public static void Main(string[] args)
{
Console.WriteLine("Performing Queue<Task> q = new Queue<Task>();");
Queue<Task> q = new Queue<Task>();
Console.WriteLine("Finished Queue<Task> q = new Queue<Task>();");
Console.WriteLine("Performing q.Enqueue(new Task(() => hello(\"world\") ) );");
q.Enqueue(new Task(() => print("hello world") ) );
Console.WriteLine("Finished q.Enqueue(new Task(() => hello(\"world\") ) );");
Console.WriteLine("Performing Task peek = q.Peek();");
Task peek = q.Peek();
Console.WriteLine("Finished Task peek = q.Peek();");
Console.WriteLine("Performing peek.Start();");
//bool temp = peek.Start(); // does not set temp to true, how do I accomplish this?
peek.Start(); // Works, but does not return true as print() should return true, how do I accomplish this?
Console.WriteLine("Finished peek.Start();");
Console.WriteLine("Performing Task dequeue = q.Dequeue();");
Task dequeue = q.Dequeue();
Console.WriteLine("Finished Task dequeue = q.Dequeue();");
Console.WriteLine("Performing dequeue.Start();");
//bool temp2 = dequeue.Start(); // does not set temp2 to true, how do I accomplish this?
dequeue.Start(); // How do I make a Task reexecute?
Console.WriteLine("Finished dequeue.Start();");
}
public static bool print(string text)
{
Console.WriteLine("print(" +text +")");
return true;
}
答案 0 :(得分:0)
以下是如何从任务获取返回值的示例:
http://msdn.microsoft.com/en-us/library/dd537613
任务的MSDN文章(http://msdn.microsoft.com/en-us/library/dd270682.aspx)说:
任务只能启动并运行一次。任何安排的尝试 第二次任务会导致异常。
我建议使用Task.Factory.StartNew()而不是新的Task()来找到重写代码的方法。开始。这是一篇关于差异的好文章:
http://blogs.msdn.com/b/pfxteam/archive/2010/06/13/10024153.aspx
为什么不排队枚举值而不是任务本身,然后编写一个小函数来根据枚举值运行任务。它可能看起来像:
public static void StartTask(Actions action)
{
if (action == Actions.Print)
{
Task t = new Task(() => print("hello world"));
t.Start();
}
}
根据第一个示例合并返回值,然后全部设置。