What's blocking is not the task itself, it's the call to Result
. A Task
represents an asynchronous operation, but calling its Result
property, or calling Wait()
will block the current thread until the method returns. And in a lot of cases, it will cause a deadlock because the task is not able to complete with it's calling thread blocked!
To prevent that, chain the tasks asynchronously, using async
and await
private async void button1_Click(object sender, EventArgs e)
{
var result = await HeavyWorkAsync(); // <=== await
richTextBox1.AppendText(result);
}
Also, Task.Delay(10).Wait();
completely defeats the prupose of using tasks in the first place: that will block the current thread. If that's really what you want to do (and it's pretty unlikely), call Thread.Sleep(10);
instead, it will make your intent much clearer, and you will have less hoops to jump through. Or better, use await Task.Delay(10);
in an async method.
About ConfigureAwait
What exactly does ConfigureAwait(false)
do?
It removes the obligation for the continuation of the task to run in the same context as the caller of the task. In most cases that means that the continuation is no longer guaranteed to run on the same context. So if I have a method thad does Foo()
, waits a little then Bar()
like this one:
async Task DoStufAsync()
{
Foo();
await Task.Delay(10);
Bar(); // run in the same context as Foo()
}
I'm guaranteed Bar will run in the same context. If I had ConfigureAwait(false)
, it's no longer the case
async Task DoStufAsync()
{
Foo();
await Task.Delay(10).ConfigureAwait(false);
Bar(); // can run on another thread as Foo()
}
When you're using ConfigureAwait(false)
, you tell your program you dont mind about the context. It can solve some deadlocking problems, but isn't usually the right solution. The right solution is most likely never to wait for tasks in a blocking way, and being asynchronous all the way.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…