An async problem

Imagine you have an asynchronous cancellable method like this:

CancellationTokenSource cts;

async Task DoSomethingAsync()
{
    if (cts != null)
        cts.Cancel();
    cts = new CancellationTokenSource();
    try
    {
        await AnAsyncMethodAsync(cts.Token);
    }
    finally
    {
        cts = null;
    }
}

And you trigger it here and there. The idea is that if it is already running when triggered (cts != null) it should send cancellation signal through its token.

Now, can you spot a possible problem that can occur?

The answer: DoSomething starts and is awaiting, another call is issued, original call is cancelled, second call is awaiting, original call advances to finally block (cts is set to null). Third call chimes in but this time cts is null (because original call set cts to null) even though second call is awaiting and thus second call is *not* cancelled, third call is awaiting and both second and third will finish.

There you go.

Leave a Reply