4

The following code (LINQPad Sample) is expected to create 5 work tasks and wait until all of them are finished.

Instead, it starts 5 tasks and immediately outputs the "... Done" - message.

The problem is the (Action) - cast after Task.Run. If I remove that cast, everything works as expected.

What happens here? It doesn't make any sense to me since in my opinion the cast is redundant.

void Main() { var tasks = Enumerable.Range(1, 5).Select(x => this.DoWork()).ToArray(); Console.WriteLine("Waiting ... "); Task.WaitAll(tasks); Console.WriteLine("... Done"); } Task DoWork() { return Task.Run( (Action)(async () => { Console.WriteLine("Task start"); await Task.Delay(3000); Console.WriteLine("Task end"); })); } 
2
  • 1
    I think you need to remove the async before the () in the task you create in DoWork. The task you create creates another task which it does not wait for and returns immediately. Commented May 26, 2014 at 11:07
  • 1
    The Task.WaitAll() method in your code does not handle the tasks with the delay, but rather the task returned from the Task.Run method. Ie, you are not waiting for the tasks. You are waiting for the tasks that created the inner tasks. The creation process is over in an instant. The inner tasks themselves will not block until you remove the "await" statement in them, so waiting for them will not make much difference. Commented May 26, 2014 at 11:10

1 Answer 1

5

I believe, it's because the async lambda (without the cast) returns Task, C# compiler chooses overload of Task.Run() method that accepts Func<Task> delegate. If you cast the delegate to Action, compiler chooses overload that accepts Action and the task returned by DoWork() method ends, when Task.Delay() method is called. The result is that Task.WaitAll() method ends before the Task.Delay() task is finished.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.