【发布时间】:2014-09-09 01:34:47
【问题描述】:
这个问题不同于await vs Task.Wait - Deadlock?。该问题涉及(据称) await 导致死锁而 .Wait 没有的情况。这个问题是反过来的。另外,提问者和回答者在另一个问题上存在分歧,所以它根本无法回答我的问题。
这会在 ASP.Net 请求的上下文中导致死锁:
protected void TestBtnClick(object sender, EventArgs e)
{
DoSomethingAsync()
.Wait();
}
private async Task DoSomethingAsync()
{
await Task.Delay(2000)
.ConfigureAwait(continueOnCapturedContext: true);
}
我的理解是,第一个调用方法在等待marshall原来的同步上下文,然后被调用的方法也等待marshall原来的上下文,从而造成死锁。
如果是这样,为什么下面的也不会导致死锁?
protected async void TestBtnClickAsync(object sender, EventArgs e)
{
await DoSomethingAsync()
// ****** DIFFERENCE IS HERE: ******
.ConfigureAwait(continueOnCapturedContext: true);
}
private async Task DoSomethingAsync()
{
await Task.Delay(2000)
.ConfigureAwait(continueOnCapturedContext: true);
}
请注意,两个异步调用都明确请求在原始同步上下文中继续。
【问题讨论】:
标签: c# asynchronous task-parallel-library deadlock