在我的 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/