'What is the point of .NET 4.6's Task.CompletedTask?

This blog post mentions the new Task APIs, including a new Task.CompletedTask property introduced in .NET 4.6.

Why was this added? How is this better than, say, Task.FromResult(whatever)?



Solution 1:[1]

Task.CompletedTask property is important when you need to give a caller a dummy Task (that doesn't return a value/result) that's already completed. This might be necessary to fulfill an "interface" contract or testing purposes.

Task.FromResult(data) also returns a dummy Task, but this time with data or a result. You probably would be doing this because you already have the data and have no need to perform any operation to get it.

Example - Task.CompletedTask

public Task DoSomethingAsync()
{
    return Task.CompletedTask; // null would throw exception on await
}

Example - Task.FromResult(data)

public Task<User> GetUserAsync()
{
    if(cachedUser != null) 
    {
        return Task.FromResult(cachedUser);
    }
    else
    {
        return GetUserFromDb();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1