“异步任务"与“返回Task.Run" [英] "async Task" vs "return Task.Run"

查看:94
本文介绍了“异步任务"与“返回Task.Run"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是异步/等待C#模型的新手,试图了解这两个选项是否本质上是同一件事:

I'm new to async/await c# model and trying to understand if these two options are essentially the same thing:

public Task LongRunningMethod()
{
    return Task.Run(async () =>
    {
        await DoStuff();
    });
}

//then call it
await LongRunningMethod();

还有这个

public async Task LongRunningMethod()
{
    await DoStuff();
}

//then call it
await LongRunningMethod();

我在想第一种方法将耗尽池中的一个额外线程...而且它还将一个Task封装为一个额外Task.还是我错了?

I'm thinking the 1st way will use up an extra thread from the pool... And it also wraps a Task into an extra Task. Or am I wrong?

推荐答案

Task.Run 将其委托排队到线程池中.这会导致两件重要的事情:

Task.Run will queue its delegate to the thread pool. This causes two important things:

  1. 第一个异步 await 之前的 DoStuff 中的任何代码都将在线程池线程上运行,而不是
  1. Any code in DoStuff before the first asynchronous await will run on a thread pool thread, instead of on the calling thread.
  2. The code in DoStuff will run in a thread pool context, instead of using whatever context was current from the calling thread.

在大多数情况下,在 Task.Run 中进行异步工作是

的错误.但这有时很有用,例如,如果 DoStuff 在异步操作之前做了一些繁重的计算工作,则可以使用 Task.Run 将其移出UI线程.

Most of the time, doing asynchronous work in Task.Run is a mistake. But it is sometimes useful, say if DoStuff does some heavy computational work before it acts asynchronously, then Task.Run could be used to move that work off of a UI thread.

这篇关于“异步任务"与“返回Task.Run"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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