我是异步/等待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:
在大多数情况下,在 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"
发布评论