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.
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"...)
See more on this question at Stackoverflow