Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to wrap a Task as a Task<TResult>

I am writing some async helper methods and I have APIs to support both Task and Task<T>. To re-use code, I'd like the Task-based API to wrap the given task as a Task<T> and just call through to the Task<T> API.

One way I can do this is:

private static async Task<bool> Convert(this Task @this)
{
    await @this.ConfigureAwait(false);
    return false;
}

However, I'm wondering: is there there is a better/builtin way to do this?

like image 493
ChaseMedallion Avatar asked Mar 20 '14 18:03

ChaseMedallion


People also ask

Is it good to use Task FromResult?

The FromResult method returns a finished Task<TResult> object that holds the provided value as its Result property. This method is useful when you perform an asynchronous operation that returns a Task<TResult> object, and the result of that Task<TResult> object is already computed.

What is a continuation Task?

A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.

Should I use Task or thread?

It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance. The task can return a result. There is no direct mechanism to return the result from a thread. Task supports cancellation through the use of cancellation tokens.

Which threading Task method will create a Task that will complete when any of the associated tasks have completed?

Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The following example calls the parameterless Wait() method to wait unconditionally until a task completes. The task simulates work by calling the Thread.


1 Answers

There is no existing Task method that does exactly this, no. Your method is fine, and is likely about as simple as you'll be able to get.

Implementing the proper error propagating/cancellation semantics using any other method is deceptively hard.

like image 83
Servy Avatar answered Sep 20 '22 07:09

Servy