Creating a task wrapper around an existing object

后端 未结 3 1106
情书的邮戳
情书的邮戳 2021-01-03 20:32

I have a method which returns a Task where the implementation may or may not need to perform a slow operation in order to retrieve the result. I would like to be able to si

相关标签:
3条回答
  • 2021-01-03 21:03

    If you have a synchronous version of the method that returns the result you can do the following

    Task<String>(()=> Hello(Name));
    

    The hello method would look like below.

    public String Hello(String Name)
    {
       return "Hello " + Name;
    }
    
    0 讨论(0)
  • 2021-01-03 21:06

    Beginning with .NET 4.5, you can use the Task.FromResult<T>() static method for exactly this purpose:

    return Task.FromResult(_Cache[key]);
    
    0 讨论(0)
  • 2021-01-03 21:09

    You could use a TaskCompletionSource<TResult>:

    var tcs = new TaskCompletionSource<Foo>();
    tcs.SetResult(_Cache[key]);
    return tcs.Task;
    

    (Note that if _Cache is a Dictionary<TKey, TValue> you could use TryGetValue to make it a single lookup.)

    0 讨论(0)
提交回复
热议问题