Reputation: 938
Wondering what is the correct way to use ConfigureAwait(false) between the following 2 ways:
var taskOne = _service.MethodOneAsync();
var taskTwo = _service.MethodTwoAsync();
var responseFromOne = await taskOne.ConfigureAwait(false);
var responseFromTwo = await taskTwo.ConfigureAwait(false);
var taskOne = _service.MethodOneAsync().ConfigureAwait(false);
var taskTwo = _service.MethodTwoAsync().ConfigureAwait(false);
var responseFromOne = await taskOne;
var responseFromTwo = await taskTwo;
Also, what is the difference in the usage between the 2 approaches.
Upvotes: 3
Views: 4447
Reputation: 14856
From the people that built and maintain the feature: ConfigureAwait FAQ
Upvotes: 3
Reputation: 43996
Ignoring whether the taskOne
and taskTwo
variables have meaningful names in the second version, both versions are functionally equivalent. Also both versions are flawed, both for the same reason, but only the first can be fixed. The problem is that in case the taskOne
fails, the taskTwo
will be leaked as a fire-and-forget task. Letting tasks run in the background unobserved, with your application having lost track of them, is not a good idea, especially if these tasks modify the state of the application while they are running. To fix this problem you must await
both tasks to complete, not each one individually:
var taskOne = _service.MethodOneAsync();
var taskTwo = _service.MethodTwoAsync();
await Task.WhenAll(taskOne, taskTwo).ConfigureAwait(false);
// At this point both tasks are completed
var resultOne = await taskOne;
var resultTwo = await taskTwo;
Obviously this fix cannot be applied in the second version, because there is no Task.WhenAll
-equivalent available for ConfiguredTaskAwaitable
structs.
This type is intended for compiler use; do not use it directly in your code.
Upvotes: 2
Reputation: 2598
as @Llama said, there are very little difference between the two.
ConfigureAwait
is simply setting which gives you a ConfiguredTaskAwaitable, which will run before the await
statement no matter which way you go.
As for why you would use ConfigureAwait
that is a diferrent issue. Traditionally this method was mainly used, (but not limited to), preventing deadlocks in your code and databases. So if you do have locks in your code, or you are referencing a database then it is a good idea to used it.
Note on Databases
These days if you are making a EF connection to an SQL db you really don't to use ConfigureAwait
. For these it has become much more safe and it is at the point where even large industries will leave it out.
However, when making ODBC calls or connecting to other type of databases it is still important.
There is a great article on it's usage here: Click Me
Upvotes: 3