zoukankan      html  css  js  c++  java
  • 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:

    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.

    答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.

    原文链接

  • 相关阅读:
    POJ 2752 Seek the Name, Seek the Fame
    POJ 2406 Power Strings
    KMP 算法总结
    SGU 275 To xor or not to xor
    hihocoder 1196 高斯消元.二
    hihoCoder 1195 高斯消元.一
    UvaLive 5026 Building Roads
    HDU 2196 computer
    Notions of Flow Networks and Flows
    C/C++代码中的笔误
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/12210413.html
Copyright © 2011-2022 走看看