What is an alternative to Task.FromResult <T> () for tasks representing operations that return void

What is the best way to return a task that does not have a parameter of a general type? In other words, a task representing an operation that returns nothing 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 should not return anything.

+6
source share
2 answers

Task<T> extends Task - therefore, it is simple enough to use Task.FromResult<object> and provide an empty result. For instance:

 Task ret = Task.FromResult<object>(null); 

(Or use a value type - it really doesn't matter much.)

Of course, since tasks are immutable, you can create one instance of this element and return it every time you want to return a completed task. (I believe the async / await framework is valid, or at least in beta versions ...)

As Assad noted, you can use Task.CompletedTask , but only if you plan to use .NET 4.6. (In fact, it is not clear whether it supports .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" ...)

+9
source

I'm not sure if this is strictly idiomatic, but for this I use Task.CompletedTask . A Task.FromResult usually used, but in all the scripts that I can think of CompletedTask , it works identically and makes more sense semantically.

+9
source

All Articles