Reputation: 3
How do I re-execute a Task, so that I may call Task.Start() multiple times?
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;
}
Upvotes: 0
Views: 98
Reputation: 1552
Here is an example of how to get a return value from a Task:
http://msdn.microsoft.com/en-us/library/dd537613
The MSDN article for Task (http://msdn.microsoft.com/en-us/library/dd270682.aspx) says that:
A task may only be started and run only once. Any attempts to schedule a task a second time will result in an exception.
I would recommend finding a way to rewrite your code using Task.Factory.StartNew() instead of new Task().Start. Here is a good article on the difference:
http://blogs.msdn.com/b/pfxteam/archive/2010/06/13/10024153.aspx
Why not queue up enum values instead of the Tasks themselves, and then write a small function to run a task based on the enum value. It could look something like:
public static void StartTask(Actions action)
{
if (action == Actions.Print)
{
Task t = new Task(() => print("hello world"));
t.Start();
}
}
Incorporate the return values based on the first example and then you're all set.
Upvotes: 0