标签:
在某种程度上,异步方法具有传染行为。当要调用一个异步方法的时候,你必须让调用异步方法的方法也变成异步形式。这种形式一直重复,直到向上移动到call stack的顶端,也就是事件处理函数。
如果这个路径中的某一个函数无法变成异步方式,这将引入一个问题。举例来说:constructors,他们不能是异步的。所以你不能在它的函数体中使用await。这时,有两个处理方式,一个是把要调用的函数变为async void形式,但是正如上一节所说的,这将让我们没有办法再await这个方法。另一种方式是我们通过调用返回的Task的Wait()函数,或者读它的Result属性,来同步的等待函数执行完成。当然,同步的代码会暂时停止应用处理消息队列,这是我们最初使用异步函数所要解决的问题,这在大多数情况下是坏主意。更糟糕的,在某些情况下,这将造成死锁。
Any synchronously called asynchronous code in InnocentLookingClass constructor is enough to cause a deadlock:
public class InnocentLookingClass() { public InnocentLookingClass() { DoSomeLengthyStuffAsync().Wait(); // do some more stuff } private async Task DoSomeLengthyStuffAsync() { await SomeOtherLengthyStuffAsync(); } // other class members } |
Let us dissect what is happening in this code.
MyEventHandler synchronously calls InnocentLookingClass constructor, which invokesDoSomeLengthyStuffAsync, which in turn asynchronously invokes SomeOtherLengthyStuffAsync. The execution of the latter method starts; at the same time the main thread blocks at Wait untilDoSomeLengthyStuffAsync completes without giving control back to the main message loop.
Eventually SomeOtherLengthyStuffAsync completes and posts a message to the message queue implying that the execution of DoSomeLengthyStuffAsync can continue. Unfortunately, the main thread is waiting for that method to complete instead of processing the messages, and will therefore never trigger it to continue, hence waiting indefinitely.
As you can see, synchronously invoking asynchronous methods can quickly have undesired consequences. Avoid it at all costs; unless you are sure what you are doing, i.e. you are not blocking the main message loop.
在返回的Task对象上调用ConfigureAwait(false);
这个方法可以避免死锁,尽管它没有办法解决【在异步调用完成之前阻塞消息循环】的问题。
from http://www.dotnetcurry.com/csharp/1307/async-await-asynchronous-programming-examples
标签:
原文地址:http://www.cnblogs.com/ddeef/p/5936188.html