为什么这个异步操作挂起? [英] Why does this async action hang?

查看:102
本文介绍了为什么这个异步操作挂起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多层次的.NET 4.5的应用程序使用C#的新的异步等待关键字调用一个方法只是挂,我不明白为什么。

I have a multi-tier .Net 4.5 application calling a method using C#'s new async and await keywords that just hangs and I can't see why.

在底部我有一个扩展区我们的数据库应用异步方法 OurDBConn (基本上是一个包装底层 DBConnection的的DBCommand 对象):

At the bottom I have an async method that extents our database utility OurDBConn (basically a wrapper for the underlying DBConnection and DBCommand objects):

public static async Task<T> ExecuteAsync<T>(this OurDBConn dataSource, Func<OurDBConn, T> function)
{
    string connectionString = dataSource.ConnectionString;

    // Start the SQL and pass back to the caller until finished
    T result = await Task.Run(
        () =>
        {
            // Copy the SQL connection so that we don't get two commands running at the same time on the same open connection
            using (var ds = new OurDBConn(connectionString))
            {
                return function(ds);
            }
        });

    return result;
}

然后,我有调用此得到一些慢速运行总计一中层异步方法:

Then I have a mid level async method that calls this to get some slow running totals:

public static async Task<ResultClass> GetTotalAsync( ... )
{
    var result = await this.DBConnection.ExecuteAsync<ResultClass>(
        ds => ds.Execute("select slow running data into result"));

    return result;
}

最后我有一个运行同步的UI方法(MVC的动作):

Finally I have a UI method (an MVC action) that runs synchronously:

Task<ResultClass> asyncTask = midLevelClass.GetTotalAsync(...);

// do other stuff that takes a few seconds

ResultClass slowTotal = asyncTask.Result;

问题是,它挂在最后一行永远。它做同样的事情,如果我称之为 asyncTask.Wait()。如果我直接运行缓慢的SQL方法,它需要大约4秒。

The problem is that it hangs on that last line forever. It does the same thing if I call asyncTask.Wait(). If I run the slow SQL method directly it takes about 4 seconds.

我期待的行为是当它到达 asyncTask.Result ,如果这还不算完,应该等到它,一旦它应该返回的结果。

The behaviour I'm expecting is that when it gets to asyncTask.Result, if it's not finished it should wait until it is, and once it is it should return the result.

如果我有一个调试器逐步执行SQL语句完成和lambda函数完成,但返回结果; GetTotalAsync的则永远无法实现。

If I step through with a debugger the SQL statement completes and the lambda function finishes, but the return result; line of GetTotalAsync is never reached.

任何想法,我做错了吗?

Any idea what I'm doing wrong?

要,我需要为了解决这一问题,调查有什么建议?

Any suggestions to where I need to investigate in order to fix this?

难道这是一个僵局的地方,如果是的话有没有什么直接的方式找到它?

Could this be a deadlock somewhere, and if so is there any direct way to find it?

推荐答案

是的,这是一个僵局的所有权利。并与TPL一个常见的​​错误,所以不心疼。

Yep, that's a deadlock all right. And a common mistake with the TPL, so don't feel bad.

当你写等待富,运行时,默认情况下,日程安排在同一个SynchronizationContext的功能的延续,该方法开始。在英语中,我们假设你从UI线程调用你的ExecuteAsync。您所查询的线程池线程上运行(因为你叫Task.Run),但你等待的结果。这意味着,运行时会安排你的返回结果;行至UI线程上跑回来,而不是安排回线程池。

When you write await foo, the runtime, by default, schedules the continuation of the function on the same SynchronizationContext that the method started on. In English, let's say you called your ExecuteAsync from the UI thread. Your query runs on the threadpool thread (because you called Task.Run), but you then await the result. This means that the runtime will schedule your "return result;" line to run back on the UI thread, rather than scheduling it back to the threadpool.

那么,如何做到这一点的僵局?想象一下,你只有这个code:

So how does this deadlock? Imagine you just have this code:

var task = dataSource.ExecuteAsync(_ => 42);
var result = task.Result;

因此​​,第一行揭开序幕异步工作。然后,第二行的块UI线程的。因此,当运行时要运行的返回结果行后面的UI线程上,它不能做到这一点,直到结果完成。但当然,不能给予的结果,直到返回反应。僵局。

So the first line kicks off the asynchronous work. The second line then blocks the UI thread. So when the runtime wants to run the "return result" line back on the UI thread, it can't do that until the Result completes. But of course, the Result can't be given until the return happens. Deadlock.

这说明了使用第三方物流的一个重要法则:当你在UI线程(或其它精美的同步上下文中)使用。结果,你必须小心,以确保没有什么任务取决于定于UI线程。否则邪恶发生。

This illustrates a key rule of using the TPL: when you use .Result on a UI thread (or some other fancy sync context), you must be careful to ensure that nothing that Task is dependent upon is scheduled to the UI thread. Or else evilness happens.

所以,你该怎么办?选项​​1是采用等待无处不在,但正如你所说这已经不是一种选择。第二个选项,可供您是简单地停止使用的await。你可以重写你的两个功能:

So what do you do? Option #1 is use await everywhere, but as you said that's already not an option. Second option which is available for you is to simply stop using await. You can rewrite your two functions to:

public static Task<T> ExecuteAsync<T>(this OurDBConn dataSource, Func<OurDBConn, T> function)
{
    string connectionString = dataSource.ConnectionString;

    // Start the SQL and pass back to the caller until finished
    return Task.Run(
        () =>
        {
            // Copy the SQL connection so that we don't get two commands running at the same time on the same open connection
            using (var ds = new OurDBConn(connectionString))
            {
                return function(ds);
            }
        });
}

public static Task<ResultClass> GetTotalAsync( ... )
{
    return this.DBConnection.ExecuteAsync<ResultClass>(
        ds => ds.Execute("select slow running data into result"));
}

有什么区别?现在有没有在任何地方等候,所以没有什么隐含地调度到UI线程。对于简单的方法,例如这些具有单个回报,有一个在做一个无功的结果=的await ...;返回结果是没有意义的图案;只是删除异步改性剂和直接传递任务的对象周围。它的开销少,如果没有别的。

What's the difference? There's now no awaiting anywhere, so nothing being implicitly scheduled to the UI thread. For simple methods like these that have a single return, there's no point in doing an "var result = await...; return result" pattern; just remove the async modifier and pass the task object around directly. It's less overhead, if nothing else.

选项#3是指定你不想让你的等待着安排回UI线程,而只是安排到UI线程。你这样做的ConfigureAwait方法,像这样:

Option #3 is to specify that you don't want your awaits to schedule back to the UI thread, but just schedule to the UI thread. You do this with the ConfigureAwait method, like so:

public static async Task<ResultClass> GetTotalAsync( ... )
{
    var resultTask = this.DBConnection.ExecuteAsync<ResultClass>(
        ds => return ds.Execute("select slow running data into result");

    return await resultTask.ConfigureAwait(false);
}

等待一个任务,如果你在它通常会安排到UI线程;等待ContinueAwait的结果会忽略你在任何情况下,始终日程安排线程池。这种方法的缺点是你要撒这个的处处的所有功能。结果你要看,因为错过任何.ConfigureAwait可能是另一个僵局的原因。

Awaiting a task normally would schedule to the UI thread if you're on it; awaiting the result of ContinueAwait will ignore whatever context you are on, and always schedule to the threadpool. The downside of this is you have to sprinkle this everywhere in all functions your .Result depends on, because any missed .ConfigureAwait might be the cause of another deadlock.

这篇关于为什么这个异步操作挂起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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