Skip to content

Running Tasks Together

The Course
•
25 min study

await one after another is sequential: each wait starts only when the last has finished. The real benefit of tasks shows when several waits overlap. That's concurrency: several things in progress at once. It isn't the same as parallelism, where several things execute at the same instant, on different CPU cores.

Start now, await later

Calling an async method starts it. Task.WhenAll gives a task that finishes when all of them have, and it returns their results in the original order, whichever finished first. Waits overlap here even on this browser's single thread, since waiting uses no thread at all. Compare the elapsed times.

Sequential versus concurrent C#
using System.Diagnostics;

var watch = Stopwatch.StartNew();
await WaitAsync(300);
await WaitAsync(300);
long sequential = watch.ElapsedMilliseconds;

watch.Restart();
int[] results = await Task.WhenAll(WaitAsync(300), WaitAsync(100));
long concurrent = watch.ElapsedMilliseconds;

Console.WriteLine(string.Join(",", results));
Console.WriteLine(sequential >= 600);
Console.WriteLine(concurrent < 550);

static async Task<int> WaitAsync(int ms)
{
    await Task.Delay(ms);
    return ms;
}
Check your prediction
Text
300,100
True
True

Parallel.For runs CPU work across cores on your own computer. Here it runs its body one iteration at a time, since there's just one thread. Waiting code behaves the same in both places, and CPU-heavy code only gets faster on your computer.

When something fails

WhenAll waits for every task, even after one fails. Then await rethrows only one of the exceptions, and you can't rely on which. All of them are still there in the task's Exception. To report all failures, keep a reference to the WhenAll task.

Two failures, one thrown C#
Task all = Task.WhenAll(FailAsync("a"), FailAsync("b"), Task.Delay(1));

try
{
    await all;
}
catch (InvalidOperationException)
{
    Console.WriteLine("caught one");
}

Console.WriteLine(all.Exception?.InnerExceptions.Count);
Console.WriteLine(string.Join(",", all.Exception!.InnerExceptions.Select(e => e.Message).Order()));

static async Task FailAsync(string name)
{
    await Task.Delay(1);
    throw new InvalidOperationException(name);
}
Check your prediction
Text
caught one
2
a,b

WhenAny

Task.WhenAny finishes as soon as the first task does, and it returns that task. It doesn't cancel the others, and it doesn't throw for a failure, so you still need to await the winner. A common use is a loop that handles results as they arrive. Task.WhenEach does that more neatly.

Handle each result as it arrives C#
var pending = new List<Task<int>> { WaitAsync(300), WaitAsync(10), WaitAsync(150) };

Task<int> first = await Task.WhenAny(pending);
Console.WriteLine(await first);

await foreach (Task<int> done in Task.WhenEach(pending))
{
    Console.WriteLine(await done);
}

static async Task<int> WaitAsync(int ms)
{
    await Task.Delay(ms);
    return ms;
}
Check your prediction
Text
10
10
150
300

Sharing state

On your own computer, continuations can run on different threads, so two tasks can change a variable at the same moment. Here's the danger: count++ is three steps (read, add, write), and two threads can interleave them and lose an update. This browser has only one thread, so a bug like this won't show up here. Learning the fix matters for that reason.

Safe in every runtime C#
int unsafeCount = 0;
int safeCount = 0;
var gate = new object();
int locked = 0;

await Task.WhenAll(Enumerable.Range(0, 100).Select(async _ =>
{
    await Task.Yield();
    unsafeCount++;
    Interlocked.Increment(ref safeCount);
    lock (gate)
    {
        locked++;
    }
}));

Console.WriteLine(safeCount);
Console.WriteLine(locked);
Console.WriteLine(unsafeCount <= 100);
Check your prediction
Text
100
100
True

unsafeCount happens to be 100 here, and on real threads it may come up short. Interlocked works for one number, and lock protects a few lines. You can't await inside a lock, and it's a compile error. The better design shares no state at all, and that's what channels offer on Day 4.

Limiting concurrency

WhenAll over a thousand tasks starts a thousand things at once. To limit that, SemaphoreSlim has a count of available slots and lets you wait for one asynchronously. Note the try and finally, so that a failure still returns its slot.

At most two at a time C#
var slots = new SemaphoreSlim(2);
var peakGate = new object();
int running = 0;
int peak = 0;

await Task.WhenAll(Enumerable.Range(1, 6).Select(WorkAsync));
Console.WriteLine(peak);

async Task WorkAsync(int id)
{
    await slots.WaitAsync();
    try
    {
        int now = Interlocked.Increment(ref running);
        lock (peakGate)
        {
            peak = Math.Max(peak, now);
        }
        await Task.Delay(5);
    }
    finally
    {
        Interlocked.Decrement(ref running);
        slots.Release();
    }
}
Check your prediction
Text
2

Look at how peak is updated. Math.Max(peak, now) reads peak, compares, and writes, so it's a read-modify-write just like count++. On real threads, one task could read 1, another write 2, and then the first write 1 back, so the reported peak would be too low. A check meant to catch "too many at once" would then pass when it shouldn't. Interlocked.Increment alone doesn't cover it, so the update gets a lock.

Your turn

Exercise

Fetch all, report each

Write FetchAllAsync(string[] urls, Func<string, Task<string>> fetch, int limit), which fetches every URL with at most limit running at once, and returns a list of results in the same order as the input. One failed fetch mustn't stop the others: each result is a record Page(string Url, string? Body, string? Error).

Use a fake that delays by a little, throws for any URL containing bad, and tracks the peak number running. Print each page, in the form a: A or bad: failed, then print the peak with a limit of 2.

When it works, it prints:

Text
a: A
bad: failed
c: C
d: D
2
Your workspace C#
#nullable enable

string[] urls = { "a", "bad", "c", "d" };
await Task.Delay(1);
Console.WriteLine(urls.Length);

record Page(string Url, string? Body, string? Error);
Hint 1: the idea

Write one method that handles one URL completely, catching its own failure so that it can't fault. Then WhenAll over it keeps the input order and never throws.

Hint 2: a first step

Put SemaphoreSlim around the fetch, with Release in a finally. Get it working with no failures before you add the catch.

Show one solution
C#
#nullable enable

string[] urls = { "a", "bad", "c", "d" };
var peakGate = new object();
int running = 0;
int peak = 0;

Page[] pages = await FetchAllAsync(urls, async url =>
{
    int now = Interlocked.Increment(ref running);
    lock (peakGate)
    {
        peak = Math.Max(peak, now);
    }
    await Task.Delay(5);
    Interlocked.Decrement(ref running);
    return url.Contains("bad") ? throw new InvalidOperationException("failed") : url.ToUpper();
}, 2);

foreach (Page page in pages)
{
    Console.WriteLine($"{page.Url}: {page.Body ?? page.Error}");
}
Console.WriteLine(peak);

static async Task<Page[]> FetchAllAsync(string[] urls, Func<string, Task<string>> fetch, int limit)
{
    var slots = new SemaphoreSlim(limit);

    async Task<Page> FetchOneAsync(string url)
    {
        await slots.WaitAsync();
        try
        {
            return new Page(url, await fetch(url), null);
        }
        catch (InvalidOperationException e)
        {
            return new Page(url, null, e.Message);
        }
        finally
        {
            slots.Release();
        }
    }

    return await Task.WhenAll(urls.Select(FetchOneAsync));
}

record Page(string Url, string? Body, string? Error);
Text
a: A
bad: failed
c: C
d: D
2

Was this article helpful?

Your response is saved on this device.