Skip to content

Tasks and await

The Course
•
25 min study

Most waiting in a program isn't work. A web request or a disk read is the computer doing nothing until the answer comes. async and await let a method give up its thread during that wait, so the same thread can do something else. Today's lessons are the foundation of the job runner.

Task is a promise

A Task<T> represents work that finishes later, with a T result. await says: "pause this method until the task finishes, and then continue with its result." While paused, the method isn't using a thread. An async method returns its task at its first real wait, so its caller continues running. Predict the order.

Who runs when? C#
Console.WriteLine("before");
Task<int> pending = LoadAsync();
Console.WriteLine("called");

int value = await pending;
Console.WriteLine(value);

static async Task<int> LoadAsync()
{
    Console.WriteLine("load: start");
    await Task.Delay(10);
    Console.WriteLine("load: resumed");
    return 42;
}
Check your prediction
Text
before
load: start
called
load: resumed
42

The method runs synchronously up to its first await on something unfinished. Top-level code can use await directly. In a class, the enclosing method must be marked async, and by convention it's named with an Async suffix.

Errors travel through the task

An exception in an async method is stored in its task and rethrown when you await it. No await, no exception: the failure disappears silently. This is why a task that's been dropped is a bug. The compiler warns about it in async methods with CS4014.

The error waits for you C#
Task failing = FailAsync();
Console.WriteLine("nothing thrown yet");
Console.WriteLine(failing.IsFaulted);

try
{
    await failing;
}
catch (InvalidOperationException e)
{
    Console.WriteLine($"caught: {e.Message}");
}

static async Task FailAsync()
{
    await Task.CompletedTask;
    throw new InvalidOperationException("boom");
}
Check your prediction
Text
nothing thrown yet
True
caught: boom

Avoid async void, which has no task to hold the exception: an error in one can bring down the whole program. Its only proper use is an event handler.

Don't block on async

.Result and .Wait() make a thread sit and wait for a task. In code with a single-threaded context, such as a UI, that thread may be the one the task needs in order to finish, which is a classic deadlock. Elsewhere, it wastes a thread. This browser runtime refuses outright, and that makes for a clear lesson: use await all the way up.

Blocking is refused here C#
Task<int> task = SlowAsync();
Console.WriteLine(task.Result);

static async Task<int> SlowAsync()
{
    await Task.Delay(10);
    return 1;
}
Check your prediction
Text
PlatformNotSupportedException
Cannot wait on monitors

On your own computer that program prints 1, because a console app has no special context, and the blocked thread is simply wasted. The habit still matters, because the same line in a UI can freeze the app.

Going further: where an await resumes

The "special context" has a name: SynchronizationContext. When an await pauses, it captures SynchronizationContext.Current, and when the task finishes it posts the rest of the method back to that context. A UI framework installs one that runs everything on the UI thread, so the code after an await in a button handler can safely touch the window. That's also how the deadlock happens: .Result holds the UI thread, and the rest of the async method is queued to run on that same thread, so each waits for the other.

Library code usually doesn't need the caller's context, because it never touches a window. It can say so with ConfigureAwait(false), which tells that await to continue on whatever thread finished the task:

No context to return to C#
Console.WriteLine(SynchronizationContext.Current is null);
int length = await ReadLengthAsync("hello");
Console.WriteLine(length);

static async Task<int> ReadLengthAsync(string text)
{
    await Task.Delay(1).ConfigureAwait(false);
    return text.Length;
}
Check your prediction
Text
True
5

The first line shows why you've never needed it in this course: console apps, this browser and ASP.NET Core have no SynchronizationContext, so ConfigureAwait(false) changes nothing there. The guidance for a library that UI apps may call is to put it on every await, because a single await without it can resume on the caller's context, and to never use it in UI code that touches controls after the await. Day 6's lesson on library boundaries comes back to this: it's a choice made for callers you can't see.

What about threads?

Task.Run asks the thread pool to run work on another thread. It's for CPU-heavy work that would otherwise hold things up, not for waiting. Don't wrap I/O in it. In this browser, it takes turns on the single thread, so the arithmetic is the same but there's no speed-up. Since new Thread().Start() isn't supported here either, this course leans on tasks, which is also what modern .NET code does.

CPU work behind a task C#
long total = await Task.Run(() =>
{
    long sum = 0;
    for (int i = 1; i <= 1000; i++)
    {
        sum += i;
    }
    return sum;
});
Console.WriteLine(total);

Task finished = Task.CompletedTask;
Console.WriteLine(finished.IsCompleted);
Console.WriteLine(await Task.FromResult(7));
Check your prediction
Text
500500
True
7

ValueTask

A Task is an object, so each one costs an allocation. When a method usually finishes without waiting (say, a cache hit), ValueTask<T> avoids that cost. It has rules, though: await it once, and don't store it. Reach for Task by default. The job runner's IJobHandler uses ValueTask<string>, since most of its jobs finish at once.

Fast path without a Task C#
var cache = new Dictionary<string, int>();

Console.WriteLine(await GetAsync("a"));
Console.WriteLine(await GetAsync("a"));
Console.WriteLine(GetAsync("a").IsCompletedSuccessfully);

async ValueTask<int> GetAsync(string key)
{
    if (cache.TryGetValue(key, out int value))
    {
        return value;
    }
    await Task.Delay(1);
    cache[key] = key.Length;
    return cache[key];
}
Check your prediction
Text
1
1
True

Your turn

Exercise

A cached lookup

Write a class Lookup that receives a Func<string, Task<string>> fetch in its constructor. GetAsync(string key) returns a cached value when it has one; otherwise it awaits fetch, stores the result and returns it. A failed fetch must not be cached: the next call should try again.

Use a lambda with a counter as the fake. It fails the first time it's asked for bad, and then returns the key in capitals. Print: GetAsync("a") twice; the number of fetches; a caught line for the failed bad; then the value for bad on a second try, and the final number of fetches.

When it works, it prints:

Text
A
A
1
caught no data
BAD
3
Your workspace C#
await Task.Delay(1);
Console.WriteLine("Start here");
Hint 1: the idea

Only store a value after await has returned successfully. An exception jumps straight past that line, so a failure is never stored.

Hint 2: a first step

Write the class around a Dictionary<string, string>. In the fake, a lambda marked async can throw, and the exception ends up in the task.

Show one solution
C#
#nullable enable

int fetches = 0;
bool failedOnce = false;

var lookup = new Lookup(async key =>
{
    fetches++;
    await Task.Delay(1);
    if (key == "bad" && !failedOnce)
    {
        failedOnce = true;
        throw new InvalidOperationException("no data");
    }
    return key.ToUpper();
});

Console.WriteLine(await lookup.GetAsync("a"));
Console.WriteLine(await lookup.GetAsync("a"));
Console.WriteLine(fetches);

try
{
    await lookup.GetAsync("bad");
}
catch (InvalidOperationException e)
{
    Console.WriteLine($"caught {e.Message}");
}
Console.WriteLine(await lookup.GetAsync("bad"));
Console.WriteLine(fetches);

class Lookup(Func<string, Task<string>> fetch)
{
    private readonly Dictionary<string, string> cache = new();

    public async Task<string> GetAsync(string key)
    {
        if (cache.TryGetValue(key, out string? cached))
        {
            return cached;
        }
        string value = await fetch(key);
        cache[key] = value;
        return value;
    }
}
Text
A
A
1
caught no data
BAD
3

Was this article helpful?

Your response is saved on this device.