【问题标题】:asyn await vs await task.run [duplicate]async await vs await task.run [重复]
【发布时间】:2020-02-26 01:23:04
【问题描述】:

使用 asyn/await 与 await task.run() 有什么区别

等待 task.run 示例 -

 public static void Main()
{

   await Task.Run(() =>
    {
        return "Good Job";
    });
    method1();
    method2();
}

异步等待示例-

 public static async void Launch()
    {

        await GetMessage();
        Method1();
        Method2();
    }

    public static async Task<string> GetMessage()
    {
        //Do some stuff
    }

【问题讨论】:

标签: c# .net async-await task-parallel-library


【解决方案1】:

区别在于代码运行的上下文。 return "Good Job"; 将在单独的任务中立即执行(并且可能在单独的线程上 - 这由默认任务调度程序确定,例如 ThreadPool)。在第二个中,第一个 await 之前 GetMessage 中的所有代码都将在与调用者相同的上下文中同步执行。 await 之后的其余代码将委托给单独的任务。

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2020-06-06
    相关资源
    最近更新 更多