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?

Avtor: Anonymous, objavljeno na portalu SloDug.si (Arhiv)

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.