skip to content

In C#, how should a Task-returning method hand back a result it already has, and what do Task.FromResult and Task.CompletedTask provide?

level: middleimportance: should knowfreq 45%

answer

  1. the cache hit path
  2. an already-finished task
  3. no async keyword needed
  4. failures keep the task contract
  5. never return null

basics

~20 s

Return Task.FromResult(value) for a Task<T>, or Task.CompletedTask for a plain Task, from a method not marked async. Both are already-completed tasks, so the caller's await continues without suspending; Task.FromException returns a faulted one for errors.

solid answer

~40 s

When an interface fixes a `Task<string> GetAsync(string city)` signature but the implementation already has the answer, such as a cache hit, the method can skip `async` and return `Task.FromResult(hit)`, a task that is already complete with that value. For a value-less `Task` the equivalent is `Task.CompletedTask`, a single shared completed instance. The caller's `await` sees a finished task and carries on at once. Errors keep the same contract with `Task.FromException<T>(ex)`, so they surface at the caller's `await`. Marking the method `async` with no `await` also works, but it builds a state machine for nothing. `Task.FromResult` still allocates a new task for most values, and a Task-returning method must never return `null`: awaiting `null` throws `NullReferenceException`.

code

csharp · 47 lines
csharp
var source = new CachedForecastSource(new SlowUpstream());

Task<string> first = source.GetAsync("Oslo");
Console.WriteLine($"first call:  IsCompleted = {first.IsCompleted}");
Console.WriteLine(await first);

Task<string> second = source.GetAsync("Oslo");
Console.WriteLine($"second call: IsCompleted = {second.IsCompleted}");
Console.WriteLine(await second);

Console.WriteLine($"WarmUpAsync returns the shared Task.CompletedTask: {ReferenceEquals(source.WarmUpAsync(), Task.CompletedTask)}");

interface IForecastSource
{
    Task<string> GetAsync(string city);
    Task WarmUpAsync();
}

sealed class SlowUpstream : IForecastSource
{
    public async Task<string> GetAsync(string city)
    {
        await Task.Delay(200); // the HTTP call
        return $"{city}: 7 C";
    }

    public Task WarmUpAsync() => Task.CompletedTask;
}

sealed class CachedForecastSource(IForecastSource upstream) : IForecastSource
{
    private readonly Dictionary<string, string> _cache = new();

    public Task<string> GetAsync(string city) =>
        _cache.TryGetValue(city, out var hit)
            ? Task.FromResult(hit) // already-completed task, no state machine
            : LoadAsync(city);

    private async Task<string> LoadAsync(string city)
    {
        var forecast = await upstream.GetAsync(city);
        _cache[city] = forecast;
        return forecast;
    }

    public Task WarmUpAsync() => Task.CompletedTask; // nothing to do, so nothing to await
}

go deeper

for a junior

Recall the helpers: Task.FromResult for a known value, Task.CompletedTask for a Task with nothing to do, and never return null.

for a middle

Explain that an already-completed task makes await continue without suspending, and when Task.FromException keeps errors inside the task contract.

for a senior

Judge hot paths: what FromResult allocates per call, when to cache the completed task, and when a pass-through without async is cleaner than an async method without await.

for a principal

Set the convention for interface implementations that are sometimes synchronous, including where usage errors throw and where runtime failures go into the task.

## The situation: the answer is already in hand Asynchronous signatures spread through interfaces. Suppose a weather client defines: ```csharp interface IForecastSource { Task<string> GetAsync(string city); Task WarmUpAsync(); } ``` One implementation calls the network. Another wraps it with an in-memory cache. On a **cache hit** the caching implementation already has the string; it must still return a `Task<string>`, because that is the contract. Its `WarmUpAsync` may have nothing to do at all. Writing a real asynchronous operation for those cases would be pointless, and the base class library provides **completed-task helpers** for them. ## The helpers | Member | Returns | Typical use | |---|---|---| | `Task.CompletedTask` | a `Task` that has already completed successfully | a `Task` method with nothing to do | | `Task.FromResult<TResult>(TResult)` | a completed `Task<TResult>` holding the value | a cache hit, a constant, a test double | | `Task.FromException(Exception)` and `Task.FromException<TResult>(Exception)` | a faulted task | reporting a failure without throwing at the call | | `Task.FromCanceled(CancellationToken)` | a canceled task | a request whose token was already canceled | The same helpers make **test doubles** simple. A fake `IForecastSource` for unit tests returns `Task.FromResult("Oslo: 7 C")` from `GetAsync` and `Task.CompletedTask` from `WarmUpAsync`, so the code under test awaits a real task with no delay and no network. For a failure path, `Task.FromException<string>(new HttpRequestException("503"))` gives a task that faults at the `await` just as a failing service call would. All of them are static members of `Task`. Awaiting any of them takes the **already-completed path**: there is no suspension, and the next line runs straight away on the same thread. Cancellation tokens themselves are covered in the lesson on cancellation. ## Walking through the caching implementation The code example implements the cache with an expression-bodied `GetAsync` that is **not** marked `async`: - On a hit it returns `Task.FromResult(hit)`. The output shows `IsCompleted = True` straight after the second call. - On a miss it returns the task of a private `async` helper that awaits the upstream service and stores the result. The output shows `IsCompleted = False` after the first call. - `WarmUpAsync` returns `Task.CompletedTask`, and the example confirms it is the same shared instance every time. The caller cannot tell the paths apart: it awaits a `Task<string>` either way. ## Why not just mark the method async ```csharp public async Task<string> GetAsync(string city) => _cache[city]; ``` This compiles and behaves correctly: an `async` method with no `await` runs to its end synchronously and returns a completed task. The objections are about cost and clarity: - The compiler still generates the async state machine and its builder for a method that never suspends. - An exception thrown inside is caught and stored in the returned task, which is what you want for runtime failures, but it is now implicit rather than visible. - Readers see `async` and expect an `await` somewhere. For a method that is purely synchronous inside, returning the helper's task directly says what happens. ## Keeping the error contract The Task-based Asynchronous Pattern says an asynchronous method should throw directly from the call **only for usage errors**, such as a null argument, and should place every other failure **in the returned task**, even when the method completes synchronously. In a non-async method that means: 1. Throw `ArgumentNullException` and similar usage errors directly, if you want them at the call. 2. Return `Task.FromException<string>(ex)` for a runtime failure, such as a corrupt cache entry, so it surfaces at the caller's `await` like any other asynchronous failure. ## Pitfalls - **Returning `null`** from a `Task`-returning method compiles, but `await` on it throws `NullReferenceException`. Return `Task.CompletedTask` or a completed `Task<T>` instead. - **`Task.FromResult(SlowLookup())` is not asynchronous.** `SlowLookup` runs to completion on the caller's thread before the task is created; the helper only wraps a value you already have. - **Allocation.** In the .NET 10 implementation, `Task.FromResult` returns cached tasks only for a few values (`null`, `true` and `false`, integers from -1 to 8, and the default of certain small value types) and allocates a new task otherwise. On a very hot path you can cache the `Task<string>` itself next to the value, or return `ValueTask<T>`, whose rules are covered in their own lesson.

  • Does Task.FromResult allocate a new task on every call?
    For most values, yes. The .NET 10 implementation hands back cached tasks for `null`, `true`, `false`, integers from -1 to 8 and the default of some small value types, and creates a new `Task<TResult>` otherwise. `Task.CompletedTask` is always one shared instance. On a hot path, cache the completed task alongside the value.
  • Why is `return null;` from a Task-returning method a bug?
    The compiler accepts it, because `Task` is a reference type, but the caller's `await` needs a task to inspect and throws `NullReferenceException` on `null`. A method with nothing to do returns `Task.CompletedTask`, and one with a known value returns `Task.FromResult(value)`.

  • A method returning a known value must be marked async to return Task<T>
  • Task.FromResult runs its argument in the background
  • Returning null from a Task method is a fine way to say nothing happened
  • Task.FromResult never allocates because completed tasks are always cached
  • A failure on a synchronous path should always be thrown from the call