在异步方法结束时,我应该返回或等待? [英] At the end of an async method, should I return or await?
问题描述
在一个任务返回异步方法结束时,如果我调用另一个异步方法,我可以为等待
,或收益
任务。这是每一个后果?
任务FooAsync()
{
返回BazAsync(); //选项A
} 异步任务BarAsync()
{
等待BazAsync(); //选项B
}
您不能如果方法本身被声明为返回任务异步
- 所以这亿韩元'T的工作,例如:
异步任务BarAsync()
{
返回BazAsync(); //无效!
}
这将需要的返回类型任务<任务方式>
如果你的方法的只是的做功少量,然后调用的只是一个异步方法,那么你的第一个选择是好的,意味着有参与少一个任务。你应该知道,在您的同步的方法将被传递抛出同步虽然任何异常 - 实际上,这是怎么了我preFER处理参数验证
这也是实现例如超载的通用模式通过取消标记。
要知道,如果你需要改变等待别的东西,你需要使它异步方法来代替。例如:
//版本1:
任务BarAsync()
{
//无需gronkle尚未...
返回BazAsync();
}//哎呀,第2版,我需要做更多的工作...
异步任务BarAsync()
{
INT gronkle =等待GronkleAsync();
//使用gronkle东西 //现在我们必须等待BazAsync正如我们在异步方法现在已经
等待BazAsync();
}
At the end of a Task-returning async method, if I call another async method, I could either await
it or return
its task. Which are the consequences of each?
Task FooAsync()
{
return BazAsync(); // Option A
}
async Task BarAsync()
{
await BazAsync(); // Option B
}
You can't return the task if the method itself is declared to be async
- so this won't work, for example:
async Task BarAsync()
{
return BazAsync(); // Invalid!
}
That would require a return type of Task<Task>
.
If your method is just doing a small amount of work and then calling just one async method, then your first option is fine, and means there's one fewer task involved. You should be aware that any exceptions thrown within your synchronous method will be delivered synchronously though - indeed, this is how I prefer to handle argument validation.
It's also a common pattern for implementing overloading e.g. by cancellation token.
Just be aware that if you need to change to await something else, you'll need to make it an async method instead. For example:
// Version 1:
Task BarAsync()
{
// No need to gronkle yet...
return BazAsync();
}
// Oops, for version 2 I need to do some more work...
async Task BarAsync()
{
int gronkle = await GronkleAsync();
// Do something with gronkle
// Now we have to await BazAsync as we're now in an async method
await BazAsync();
}
这篇关于在异步方法结束时,我应该返回或等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!