Task.FromResult<TResult> 有什么用?在 C# 中 [英] What is the use for Task.FromResult&lt;TResult&gt; in C#

查看:22
本文介绍了Task.FromResult<TResult> 有什么用?在 C# 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 和 TPL(任务并行库)中,Task class 表示正在进行的工作,该工作产生类型 T 的值.

In C# and TPL (Task Parallel Library), the Task class represents an ongoing work that produces a value of type T.

我想知道 Task.FromResult 方法需要什么?

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?

唯一想到的是它被用作接受 Task 实例的其他方法的一些适配器.

The only thing that comes to mind is that it's used as some adapter for other methods accepting a Task instance.

推荐答案

我发现了两个常见的用例:

There are two common use cases I've found:

  1. 当您实现一个允许异步调用者的接口,但您的实现是同步的.
  2. 当您存根/模拟异步代码进行测试时.

这篇关于Task.FromResult<TResult> 有什么用?在 C# 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆