await await vs Unwrap()

微笑、不失礼 提交于 2020-03-17 07:59:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!