Cary
Cary

Reputation: 393

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;

Update: Someone marked my question as a duplicate of this one: Awaiting multiple Tasks with different results. The question is different, which is why I didn't find it in my searches, though one of the detailed answers there does answer may question, also.

Upvotes: 11

Views: 3814

Answers (2)

Felipe Sabino
Felipe Sabino

Reputation: 18215

The doc says that Task.Result it is equivalent to calling the Wait method.

And when Wait is called

“What does Task.Wait do?”

... If the Task ran to completion, Wait will return successfully.

(from https://blogs.msdn.microsoft.com/pfxteam/2009/10/15/task-wait-and-inlining/)

So you can assume that when you call Task.Result, it will return successfully not leading to the deadlocks you mentioned.

Upvotes: 3

StriplingWarrior
StriplingWarrior

Reputation: 156524

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;

Upvotes: 6

Related Questions