Given a method such as
public async Task<Task> ActionAsync() { ... }
What is the difference between
await await ActionAsync();
and
await ActionAsync().Unwrap();
if any.
Result() it blocks the thread until a result is returned before continuing to the next line of code. When you use await you are also awaiting an synchronous call to complete before the code following t (continuation step).
We know now that await doesn't block - it frees up the calling thread.
Unwrap() - A useful proxy to avoid inner Task inside a Task.
The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.
Unwrap()
creates a new task instance that represent whole operation on each call. In contrast to await
task created in such a way is differ from original inner task. See the Unwrap() docs, and consider the following code:
private async static Task Foo() { Task<Task<int>> barMarker = Bar(); Task<int> awaitedMarker = await barMarker; Task<int> unwrappedMarker = barMarker.Unwrap(); Console.WriteLine(Object.ReferenceEquals(originalMarker, awaitedMarker)); Console.WriteLine(Object.ReferenceEquals(originalMarker, unwrappedMarker)); } private static Task<int> originalMarker; private static Task<Task<int>> Bar() { originalMarker = Task.Run(() => 1);; return originalMarker.ContinueWith((m) => m); }
Output is:
True False
Update with benchmark for .NET 4.5.1: I tested both versions, and it turns out that version with double await
is better in terms of memory usage. I used Visual Studio 2013 memory profiler. Test includes 100000 calls of each version.
x64:
╔══════════════════╦═══════════════════════╦═════════════════╗ ║ Version ║ Inclusive Allocations ║ Inclusive Bytes ║ ╠══════════════════╬═══════════════════════╬═════════════════╣ ║ await await ║ 761 ║ 30568 ║ ║ await + Unwrap() ║ 100633 ║ 8025408 ║ ╚══════════════════╩═══════════════════════╩═════════════════╝
x86:
╔══════════════════╦═══════════════════════╦═════════════════╗ ║ Version ║ Inclusive Allocations ║ Inclusive Bytes ║ ╠══════════════════╬═══════════════════════╬═════════════════╣ ║ await await ║ 683 ║ 16943 ║ ║ await + Unwrap() ║ 100481 ║ 4809732 ║ ╚══════════════════╩═══════════════════════╩═════════════════╝
There won't be any functional difference.
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