c# - 如果我在一个方法中有两个 await Task.Run(),第二个会等待第一个完成吗?

标签 c# asynchronous

在我的 OnStart 中,我需要运行获取数据的代码,然后运行 ​​CheckScore 方法。 GetData 必须在 CheckScore 运行之前完成。这也是调用方法的正确方法吗? Method()CheckScore() 都不是异步运行的。

谁能告诉我这样做是否有区别:

protected override async void OnStart()
{
    await Task.Run(() => Method());
}

public void Method() 
{
    App.DB.GetData();
    PointChecker.CheckScore();
}

或者像这样:

protected override async void OnStart()
{
    await Task.Run(() => Method());
    await Task.Run(() => PointChecker.CheckScore());
}

public void Method() 
{
    App.DB.GetData();
}

最佳答案

will the second wait for the first to complete?

是的。第一个 await 下面的任何代码:

await Task.Run(() => Method());

等待直到执行完成。

Can someone tell me if there is a difference...

在您的简化示例中,基本上没有区别。您有一个在内部同步和顺序运行的 async 方法。

如果你想在此期间完成任何其他工作,你可以将等待时间设置得稍晚一些:

protected override async void OnStart()
{
    Task methodTask = Task.Run(() => Method());

    // do anything here while the Task runs

    await methodTask; // wait here so that CheckScore() is not started yet

    await Task.Run(() => PointChecker.CheckScore());
}

I was thinking that using Await would allow the OnStart() to finish so that the UI could update.

由于您已将 OnStart 声明为“async”,因此它不会阻塞 UI,它会保持响应。由于您的示例中没有返回值和更新代码。这是我的答案,无需过多假设。

关于c# - 如果我在一个方法中有两个 await Task.Run(),第二个会等待第一个完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52145629/

相关文章:

c# - SetWindowPos 插入之后,而不是之前?

c# - 虚函数 C#

System.Windows.Forms.Button 类的 C# 自定义属性

iphone - 加载和解析 xml 文档卡住了 Iphone 中的 GUI

javascript - 如何在 Node.js 中高效处理大量数据?

c# - 寻找特定日期

c# - 调度定时器构造函数

C++:std::async 和 std::mutex 在 Linux 上导致死锁但在 Windows 上运行?

c# - 是否有实现异步游戏引擎循环的最佳实践?

javascript - 对 SQL 查询进行排队