Why am I getting WaitingforActivation TaskStatus

I am trying to use async and wait for a command in the form with VS2012 framework 4.5. My async method SlowMethodAsync returns nothing. Please note that this code works great 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;
}
+5
source share
1 answer

You are at an impasse.

Using task.Resultblocks the user interface thread — it cannot complete before the task returned is complete SlowMethodAsync.

However, since it SlowMethodAsyncwas originally launched with the synchronization context also in the user interface thread, the continuation after awaitalso wants to be performed in the user interface thread.

Result , async... async Result.

button1_Click, :

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

, , , SlowMethodAsync , , , "" , .

+5

All Articles