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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With