Cary Cary - 1 month ago 3
C# Question

Is it ok to call task.Result in an async method if you know the task is completed?

I understand that calling

task.Result
in an
async
method can lead to deadlocks. I have a different twist on the question, though...

I find myself doing this pattern a lot. I have several tasks that return the same types of results, so I can await on them all at once. I want to process the results separately, though:

Task<int> t1 = m1Async();
Task<int> t2 = m2Async();
await Task.WhenAll(t1, t2);


Is it ok to call
Result
here, since I know the tasks are now completed?

int result1 = t1.Result;
int result2 = t2.Result;


Or, should I use
await
still...it just seems redundant and can be a bit uglier depending on how I need to process the results:

int result1 = await t1;
int result2 = await t2;

Answer

There's nothing inherently wrong or bad about using t1.Result after you've already done an await, but you may be opening yourself up to future issues. What if someone changes the code at the beginning of your method so you can no longer be positive the Tasks have completed successfully? And what if they don't see your code further down that makes this assumption?

Seems to me that it might be better to use the returned value from your first await.

Task<int> t1 = m1Async();
Task<int> t2 = m2Async();
var results = await Task.WhenAll(t1, t2);

int result1 = results[0];
int result2 = results[1];

That way, if someone messes with the first await, there's a natural connection for them to follow to know that your code later is dependent on its result.

You may also want to consider whether Task.WhenAll() is really giving you any value here. Unless you're hoping to tell the difference between one task failing and both failing, it might just be simple to await the tasks individually.

Task<int> t1 = m1Async();
Task<int> t2 = m2Async();

int result1 = await t1;
int result2 = await t2;