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.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
If you forget to use await while calling an async function, the function starts executing. This means that await is not required for executing the function. The async function will return a promise, which you can use later.
Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.
A synchronous method calls an async method, obtaining a Task . The synchronous method does a blocking wait on the Task .
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With