“异步任务"与“返回Task.Run"

编程入门 行业动态 更新时间:2024-10-27 02:19:33
本文介绍了“异步任务"与“返回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:

  • 第一个异步 await 之前的 DoStuff 中的任何代码都将在线程池线程上运行,而不是在调用线程上.
  • DoStuff 中的代码将在线程池上下文中运行,而不是使用来自调用线程的最新上下文.
  • Any code in DoStuff before the first asynchronous await will run on a thread pool thread, instead of on the calling thread.
  • 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"

    本文发布于:2023-11-03 07:42:18,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1554598.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:quot   Task   Run

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!