使用方法ASYC等待Task.Run()从未与QUOT;完成" [英] Asyc method using await Task.Run() never "completes"

查看:161
本文介绍了使用方法ASYC等待Task.Run()从未与QUOT;完成"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有被定义为

public async Task SomeAsyncMethod()
{
   DoSomeStuff();
   await Task.Run(() => {
     DoSomeSyncStuff();
     DoSomeOtherSyncStuff();
   });
   var someDebugVariable = "someDebugValue";
}

该方法本身不正是它应该做的,一切都正常运行。然而......它看起来像外异步工作永远不会完成。

例如:当我这样称呼它

public void CallerMethod()
{
   Task t = SomeAsyncMethod();
   t.Wait();
}

t.Wait()永远不会完成。另外:如果我把一个断点的分配 someDebugVariable 它从来没有被击中

the t.Wait() never completes. Furthermore: if I place a breakpoint at the assignment of someDebugVariable it never gets hit.

我想补充一点 DoSomeSyncStuff DoSomeOtherSyncStuff 真正做什么,他们都应该通过他们的调试告诉我,他们都完成了。

I might add that DoSomeSyncStuff and DoSomeOtherSyncStuff really do what they are supposed to and debugging through them tells me that they both complete.

要证明我的观点我修改我的方法是这样,结果还是一样。

To prove my point I modified my method like this, and the results are still the same.

public async Task SomeAsyncMethod()
{
   DoSomeStuff();
   await Task.Run(() => {
     /*
     DoSomeSyncStuff();
     DoSomeOtherSyncStuff();
     */
     var a = 2; var b = 3; var c = a + b;
   });
   var someDebugVariable = "someDebugValue";
}

修改

我曾尝试去除一切,但等待Task.Run ,它不会改变任何东西。它仍然没有完成。

I have tried removing everything but the await Task.Run and it does not change anything. It still does not complete.

应用程序是一个WPF应用程序。调用者线程是UI线程。

The application is a WPF application. The caller thread is the UI thread.

我是什么在这里失踪?

推荐答案

该t.Wait()调用导致死锁,也使得异步调用完全没有意义的。我相信,如果你改变了code到

The t.Wait() call is causing a deadlock, and also makes the async call entirely pointless. I believe if you change the code to

await Task.Run(() => {
// ...
}).ConfigureAwait(false);

您可以修复僵局,让code继续,但是你应该摆脱t.Wait()的调用。要与同步函数调用应等待任务后进行的,而不是异步函数的调用后的结果做任何需要。

You can fix the deadlock and let the code proceed, but you should really get rid of the t.Wait() call. Anything that needs to be done with the results of the sync function calls should be done after the awaited task, not after the call of the async function.

在深入更多:
task.Wait()将在任务运行时阻塞主线程上执行所有。当等待任务完成时,它会尝试马歇尔回到主线程,但主线程被阻塞!由于A正在等待B,而B等待,你就会得到一个僵局。

More in depth: task.Wait() will block all execution on the main thread while the task is running. When the await task completes, it tries to marshall back to the main thread, but the main thread is blocked! Since A is waiting for B, and B is waiting for A, you get a deadlock.

请参阅:<一href=\"http://blog.stephencleary.com/2012/07/dont-block-on-async-$c$c.html\">http://blog.stephencleary.com/2012/07/dont-block-on-async-$c$c.html

这篇关于使用方法ASYC等待Task.Run()从未与QUOT;完成&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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