异步CTP错误 - 任务无法完成 [英] Async CTP Bug - Task Never Completes

查看:228
本文介绍了异步CTP错误 - 任务无法完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先向前道歉:我不能隔离以下错误成一个简单的控制台应用程序。然而,在我相对简单的ASP.NET Web窗体应用程序,以下code将使当前线程无限期阻塞:

Firstly a forward apology: I cannot isolate the following bug into a simple console application. However, in my relatively simple ASP.NET Web Forms application, the following code will cause the current thread to block indefinitely:

public class MyModule : IHttpModule
{
    public void Dispose()
    {
    }

    public void Init(System.Web.HttpApplication context)
    {
        context.BeginRequest += this.Context_BeginRequest;
    }

    private void Context_BeginRequest(object sender, EventArgs e)
    {
        Sleep().Wait();
        var x = 2; // This line is never hit.
    }

    private async Task Sleep()
    {
        await TaskEx.Run(() => System.Threading.Thread.Sleep(1000));
    }
}

任务状态只保持为WaitingForActivati​​on。没有人知道为什么会发生这种事?

The task state just remains as 'WaitingForActivation'. Does anyone know why this would happen?

推荐答案

编辑:从斯蒂芬·克利本评论揭示更多的光:

The comment from Stephen Cleary sheds more light:

AspNetSynchronizationContext 是奇怪的执行。它把邮政的同步,而不是异步和的使用锁定的时间执行其代表之一。 AspNetSynchronizationContext 不需要封送回到同一个线程(但需要采取锁);在等待僵局是因为延续正在等待锁(在事件处理程序的线程持有)

AspNetSynchronizationContext is the strangest implementation. It treats Post as synchronous rather than asynchronous and uses a lock to execute its delegates one at a time. AspNetSynchronizationContext does not require marshaling back to the same thread (but does need to take the lock); the deadlock on Wait is because the continuation is waiting for the lock (held by the thread in the event handler)

我的猜到的是,有一个的SynchronizationContext 这是迫使延续在同一个线程事件处理程序运行。事件处理程序阻止该线程,所以从来运行的延续,这意味着事件处理程序将永远的疏通的。


My guess is that there's a SynchronizationContext which is forcing the continuation to run on the same thread as the event handler. Your event handler is blocking that thread, so the continuation never runs, which means the event handler will never unblock.

这只是一个猜测,虽然 - 这是我唯一能想到这是有意义的时刻

That's only a guess though - it's the only thing I can think of which makes sense at the moment.

一个选项的尝试的解除封锁这是你的睡眠方法更改为:

One option to try to unblock this is to change your Sleep method to:

private async Task Sleep()
{
    await TaskEx.Run(() => System.Threading.Thread.Sleep(1000))
                .ConfigureAwait(continueOnCapturedContext: false);
}

这将允许继续完成在不同的环境中。

That will allow the continuation to complete on a different context.

我很惊讶有的的这种同步环境,你要知道......我期望这一切只发生在线程池。也许的BeginRequest 被视为略显特殊。

I'm surprised there is such a synchronization context, mind you... I'd expect all of this to just happen on the thread pool. Possibly BeginRequest is treated slightly specially.

这篇关于异步CTP错误 - 任务无法完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆