本文介绍了等待await vs Unwrap()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出诸如
public async Task<Task> ActionAsync() { ... }两者之间有什么区别
await await ActionAsync();和
await ActionAsync().Unwrap();(如果有).
推荐答案Unwrap()创建一个新的任务实例,该实例代表每个调用的整个操作.与以这种方式创建的await任务相反,它与原始内部任务不同.请参见 Unwrap()文档,以及考虑以下代码:
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); }输出为:
True False使用.NET 4.5.1的基准更新:我测试了两个版本,事实证明,具有双await的版本在内存使用方面更好. 我使用了Visual Studio 2013内存探查器.测试包括每个版本的100000次调用.
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 ║ ╚══════════════════╩═══════════════════════╩═════════════════╝更多推荐
等待await vs Unwrap()
发布评论