Is it bad practice to call await on a task that has already been waited on? 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.
In your specific case, I would just use .Result
. There is no reason to await
on the completed Task
to get the result. 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,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.