是否使用带有“Task.Run()"冗余的“异步"lambda? [英] is using an an `async` lambda with `Task.Run()` redundant?

查看:25
本文介绍了是否使用带有“Task.Run()"冗余的“异步"lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了一些代码,例如:

I just came across some code like:

var task = Task.Run(async () => { await Foo.StartAsync(); });
task.Wait();

(不,我不知道 Foo.StartAsync() 的内部工作原理).我最初的反应是去掉 async/await 并重写为:

(No, I don't know the inner-workings of Foo.StartAsync()). My initial reaction would be get rid of async/await and rewrite as:

var task = Foo.StartAsync();
task.Wait();

这是否正确(同样,对 Foo.StartAsync() 一无所知).这个它有什么不同 - 使用 Task.Run 运行异步"动作委托...... 似乎表示可能有可能有意义的情况,但它也说说实话,我没有见过那么多场景......"

Would that be correct, or not (again, knowing nothing at all about Foo.StartAsync()). This answer to What difference does it make - running an 'async' action delegate with a Task.Run ... seems to indicate there may be cases when it might make sense, but it also says "To tell the truth, I haven't seen that many scenarios ..."

推荐答案

通常Task.Run预期用法是执行非 UI 线程上的 CPU 绑定代码.因此,它很少与 async 委托一起使用,但它是可能的(例如,对于同时具有异步和 CPU 绑定部分的代码).

Normally, the intended usage for Task.Run is to execute CPU-bound code on a non-UI thread. As such, it would be quite rare for it to be used with an async delegate, but it is possible (e.g., for code that has both asynchronous and CPU-bound portions).

然而,这是预期的用途.我认为在你的例子中:

However, that's the intended usage. I think in your example:

var task = Task.Run(async () => { await Foo.StartAsync(); });
task.Wait();

更有可能的是,原作者试图同步阻塞异步代码,并且 (ab) 使用 Task.Run避免这种情况下常见的死锁(正如我在我的博客中所描述的那样).

It's far more likely that the original author is attempting to synchronously block on asynchronous code, and is (ab)using Task.Run to avoid deadlocks common in that situation (as I describe on my blog).

本质上,它看起来像我在 关于棕地异步代码的文章.

In essence, it looks like the "thread pool hack" that I describe in my article on brownfield asynchronous code.

最佳解决方案是不使用Task.Run Wait:

The best solution is to not use Task.Run or Wait:

await Foo.StartAsync();

这将导致 async 在您的代码库中增长,这是最好的方法,但现在可能会给您的开发人员带来不可接受的工作量.这大概就是你的前任使用 Task.Run(..).Wait().

This will cause async to grow through your code base, which is the best approach, but may cause an unacceptable amount of work for your developers right now. This is presumably why your predecessor used Task.Run(..).Wait().

这篇关于是否使用带有“Task.Run()"冗余的“异步"lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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