What is the best way to return a task that doesn't have a generic type parameter? In other words a task that represents an operation that doesn't return anything or returns void?
In other words, I am looking for alternatives for the following:
T value = default(T);
return Task.FromResult<T>(value); // and
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(value);
return tcs.Task;
But for tasks that represent operations that are not supposed to return anything.
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.
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. Show activity on this post. Use the Task. FromResult when you want to have a asynchronous operation but sometimes the result is in hand synchronously.
The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.
C# Language Async-Await Returning a Task without awaitThere is only one asynchronous call inside the method. The asynchronous call is at the end of the method. Catching/handling exception that may happen within the Task is not necessary.
I'm not sure if this is strictly idiomatic, but I use Task.CompletedTask for this. A Task.FromResult is commonly used, but in all scenarios I can think of CompletedTask works identically, and makes more sense semantically.
Task<T> extends Task - so it's reasonably common to just use Task.FromResult<object> and provide an empty result. For example:
Task ret = Task.FromResult<object>(null);
(Or use a value type - it really doesn't matter much.)
Of course, as tasks are immutable you could create a singleton instance of this and return it every time you want to return a completed task. (I believe that's what the async/await infrastructure does, in fact - or at least did in beta releases...)
As Asad noted, you can use Task.CompletedTask, but only if you're targeting .NET 4.6. (Actually, it's not clear whether it's supporting in .NET 4.5 or not - the documentation shows ".NET Framework 4.6 and 4.5" as the version number, but then says "Supported in: 4.6"...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With