Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a WaitingforActivation TaskStatus

Tags:

c#

I am trying to use async and await commands on a form with VS2012 framework 4.5. My async method SlowMethodAsync does not return anything. Note this code works fine in a Console application.

private void button1_Click(object sender, EventArgs e)
{
    var task =  SlowMethodAsync();

    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }

    System.Threading.Tasks.TaskStatus status = task.Status;

     Console.WriteLine("Slow method result on Thread: {0}", task.Result);    //This line never executes
    Console.WriteLine("Main complete on {0}", Thread.CurrentThread.ManagedThreadId);
}

//Why is this method not returning anything?

static async Task<int> SlowMethodAsync()
{
    Console.WriteLine("Slow method started on Thread: {0}", Thread.CurrentThread.ManagedThreadId);

    await Task.Delay(2000);

    Console.WriteLine("Slow method complete on Thread: {0}", Thread.CurrentThread.ManagedThreadId);

    return 42;
}
like image 787
user2221178 Avatar asked Mar 28 '13 19:03

user2221178


1 Answers

You've caused a deadlock.

Using task.Result blocks the UI thread - it can't complete until the task returned by SlowMethodAsync completes.

However, because SlowMethodAsync was originally launched with a synchronization context also on the UI thread, the continuation after await also wants to execute on the UI thread.

So Result can't complete until the async method completes... and the async method can't complete until Result has completed.

Instead, you should make your button1_Click method async too, and then use:

Console.WriteLine("Slow method result on Thread: {0}", await task); 

The reason this would have worked in a console app was that the SlowMethodAsync method wouldn't have had any particular synchronization context to come back to, so the continuation could execute on any thread pool thread - which wouldn't be blocked by the "main" thread waiting on the task.

like image 131
Jon Skeet Avatar answered Nov 16 '22 22:11

Jon Skeet