我刚接触 async/await,希望确认以下的做法是否正确:
public async Task DoHeavyWorkAsync()
{
await Task.Run(() => {
getResponseFromFarawaySlowServerAndDoSomethingWithIt();
});
}
public async void ConsumeAsync()
{
Task longRunningTask = DoHeavyWorkAsync();
// do a lot of other stuffs here that does not depend on DoHeavyWorkAsync()
await longRunningTask;
}
这种使用async/await的方式正确吗,或者我做错了什么?
ConsumeAsync
函数中缺少了async
关键字。 - Yuval ItzchakovgetResponseFromFarawaySlowServerAndDoSomethingWithIt
设为异步,那么请这样做,而不是用Task.Run
包装它。 - dcastro