一个简单的 ValueTask 的示例
2019-07-30 18:20 音乐让我说 阅读(557) 评论(0) 编辑 收藏 举报 Task
确实有潜在的缺点,特别是对于实例创建很多 并且高吞吐量和性能是关键问题的场景 : Task
是一个类。作为一个类,这意味着任何需要创建一个对象的操作都需要分配一个对象,分配的对象越多,垃圾收集器(GC)需要做的工作就越多,我们花在它上面的资源就越多可以花在做其他事情上。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ValueTaskSample { class Program { static async Task Main(string[] args) { for (int i = 0; i < 20; i++) { IEnumerable<string> data = await GetSomeDataAsync(); await Task.Delay(1000); } Console.ReadLine(); } private static DateTime _retrieved; private static IEnumerable<string> _cachedData; public static async ValueTask<IEnumerable<string>> GetSomeDataAsync() { if (_retrieved >= DateTime.Now.AddSeconds(-5)) { Console.WriteLine("{0} : data from the cache", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); return await new ValueTask<IEnumerable<string>>(_cachedData); } Console.WriteLine("{0} : data from the service.", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); (_cachedData, _retrieved) = await GetTheRealData(); return _cachedData; } public static Task<(IEnumerable<string> data, DateTime retrievedTime)> GetTheRealData() => Task.FromResult( (Enumerable.Range(0, 10) .Select(x => $"item {x}").AsEnumerable(), DateTime.Now)); } }
参考:https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步