等待await vs Unwrap()

编程入门 行业动态 更新时间:2024-10-26 22:16:42
本文介绍了等待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()

本文发布于:2023-11-06 10:01:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563385.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:await   Unwrap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!