[英]Is calling await multiple time on the same task bad for performance
Is it bad practice to call await on a task that has already been waited on? 在已经等待的任务上调用await是不好的做法吗? Is it bad for performance?
对性能不好吗?
class SomeClass
{
string Prop1;
string Prop2;
}
public void SomeMethod()
{
Task<SomeClass>[] someClassInstanceTasks = Task<SomeClass>[10];
foreach(var task in someClassInstanceTasks)
{
task = GetSomeClassInstanceAsync();
}
someClassInstanceTasks.WaitAll();
SomeClass someClassInstance = someClassInstanceTasks[0].Result;
//OR (which is recommended)
SomeClass someClassInstance = await someClassInstanceTasks[0];
}
Personally, I prefer the await approach as an additional safeguard in case someone introduced a bug and mucked with the WaitAll() statement. 就个人而言,我更喜欢使用await方法作为额外的保护措施,以防万一有人引入了错误并混入了WaitAll()语句。
In your specific case, I would just use .Result
. 在您的特定情况下,我只会使用
.Result
。 There is no reason to await
on the completed Task
to get the result. 没有理由
await
完成的Task
来获得结果。 There is however a reason why you wouldn't want to await
on a completed Task
, simply due to the fact that you need to mark your method async
, which will cause you to mark up all methods that calls that one either async
or you would have to implement TaskCompletion
, which is a lot of effort for no gain, 但是,有一个原因使您不想
await
已完成的Task
,仅仅是因为您需要将方法标记为async
,这会导致您标记所有调用该方法的async
方法,或者必须实现TaskCompletion
,这是TaskCompletion
,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.