在 C# 中 Task.FromResult<TResult> 有什么用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19568280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:18:58  来源:igfitidea点击:

What is the use for Task.FromResult<TResult> in C#

c#.nettask-parallel-librarytaskasync-await

提问by lysergic-acid

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

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

I'd like to know what is the need for the Task.FromResultmethod ?

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

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.

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

采纳答案by Stephen Cleary

There are two common use cases I've found:

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

  1. When you're implementing an interface that allows asynchronous callers, but your implementation is synchronous.
  2. When you're stubbing/mocking asynchronous code for testing.
  1. 当您实现一个允许异步调用者的接口时,但您的实现是同步的。
  2. 当您存根/模拟异步代码进行测试时。

回答by Matt Smith

One example would be a method that makes use of a cache. If the result is already computed, you can return a completed task with the value (using Task.FromResult). If it is not, then you go ahead and return a task representing ongoing work.

一个例子是使用缓存的方法。如果结果已经计算出来,你可以返回一个已完成的带有值的任务(使用Task.FromResult)。如果不是,那么您继续并返回一个代表正在进行的工作的任务。

Cache Example: Cache Example using Task.FromResult for Pre-computed values

缓存示例:使用 Task.FromResult 进行预计算值的缓存示例

回答by goughy000

From MSDN:

来自 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.

当您执行返回 Task 对象的异步操作并且该 Task 对象的结果已经计算时,此方法很有用。

http://msdn.microsoft.com/en-us/library/hh228607.aspx

http://msdn.microsoft.com/en-us/library/hh228607.aspx

回答by Alborz

Use the Task.FromResult when you want to have a asynchronous operation but sometimes the result is in hand synchronously. You can find a good sample here http://msdn.microsoft.com/en-us/library/hh228607.aspx.

当您想要异步操作但有时结果是同步的时,请使用 Task.FromResult。您可以在这里找到一个很好的示例http://msdn.microsoft.com/en-us/library/hh228607.aspx

回答by Edminsson

Use it when you want to create an awaitable method without using the async keyword. I found this example:

当您想在不使用 async 关键字的情况下创建可等待方法时使用它。我找到了这个例子:

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.

在这里,您将创建自己的 IHttpActionResult 接口实现,以在 Web Api 操作中使用。ExecuteAsync 方法应该是异步的,但您不必使用 async 关键字使其异步和可等待。由于您已经有了结果并且不需要等待任何东西,因此最好使用 Task.FromResult。

回答by Viking

I would argue that you could use Task.FromResult for methods that are synchronous that take a long time to complete while you can do other independent work in your code. Id rather make those methods to call async though. But imagine the situation where you have no control over the code called and you want that implicit parallel processing.

我认为您可以将 Task.FromResult 用于需要很长时间才能完成的同步方法,同时您可以在代码中执行其他独立工作。我宁愿让这些方法调用异步。但是想象一下您无法控制调用的代码并且您想要隐式并行处理的情况。