给定诸如

public async Task<Task> ActionAsync()
{
    ...
}

之间有什么区别
await await ActionAsync();


await ActionAsync().Unwrap();

如果有的话。

最佳答案

Unwrap()创建一个新的任务实例,该实例代表每个调用的整个操作。与以这种方式创建的await任务相反,该任务不同于原始内部任务。请参阅Unwrap()文档,并考虑以下代码:

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);
}

输出为:
True
False

使用.NET 4.5.1的基准测试更新:我测试了两个版本,事实证明,使用双await的版本在内存使用方面更好。
我使用了Visual Studio 2013内存分析器。测试包括每个版本的100000个调用。

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         ║
╚══════════════════╩═══════════════════════╩═════════════════╝

关于c# - 等待await vs Unwrap(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34816628/

10-11 02:03