What is the use for Task.FromResult<TResult> in C#(转载)
问:
In C# and TPL (Task Parallel Library), the Task class represents an ongoing work that produces a value of type T.
I'd like to know what is the need for the Task.FromResult method ?
That is: In a scenario where you already have the produced value at hand, what is the need to wrap it back into a Task?
The only thing that comes to mind is that it's used as some adapter for other methods accepting a Task instance.
答1:
There are two common use cases I've found:
- When you're implementing an interface that allows asynchronous callers, but your implementation is synchronous.
- When you're stubbing/mocking asynchronous code for testing.
答2:
Use it when you want to create an awaitable method without using the async keyword. I found this example:
public class TextResult : IHttpActionResult { string _value; HttpRequestMessage _request; public TextResult(string value, HttpRequestMessage request) { _value = value; _request = request; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = new HttpResponseMessage() { Content = new StringContent(_value), RequestMessage = _request }; return Task.FromResult(response); } }
Here you are creating your own implementation of the IHttpActionResult interface to be used in a Web Api Action. The ExecuteAsync method is expected to be asynchronous but you don't have to use the async keyword to make it asynchronous and awaitable. Since you already have the result and don't need to await anything it's better to use Task.FromResult.
From MSDN:
This method is useful when you perform an asynchronous operation that returns a Task object, and the result of that Task object is already computed.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2019-01-18 Json.NET如何避免循环引用
2019-01-18 在AspNetCore 中 使用Redis实现分布式缓存 (转载)
2019-01-18 Windows下安装Redis
2010-01-18 ASP.NET视图的保存与加载解析(二)——视图的加载
2010-01-18 ASP.NET视图的保存与加载解析(一)——视图的保存