问题
Given a method such as
public async Task<Task> ActionAsync()
{
...
}
What is the difference between
await await ActionAsync();
and
await ActionAsync().Unwrap();
if any.
回答1:
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 ║
╚══════════════════╩═══════════════════════╩═════════════════╝
回答2:
There won't be any functional difference.
来源:https://stackoverflow.com/questions/34816628/await-await-vs-unwrap