Even simple stuff, like C# TPL can surprise you!

What do you think would happen if you run this code? Can you guess without actually running it?
Now try running it and see what happens. It might actually surprise you…

I know I was surprised by this, it took me a minute or two and a glimpse into relevant documentation page to understand what happened here.
The backgroundTask in the above code is actually a continuation task, and not the background worker. Since the background worker runs successfully, the continuation task is canceled, as it should. Actually, the code above should be rewritten like this:

1
2
3
4
5
6
7
8
9
10
11
var backgroundTask = Task.Run(() =>
{
Thread.Sleep(2000); //simulate some work
});

backgroundTask.ContinueWith(_ =>
{
Console.WriteLine("Running the continuation!");
}, TaskContinuationOptions.NotOnRanToCompletion);

await backgroundTask; //we registered the continuation, now we can wait for the worker...

All in all, I think it was a nice little issue. Also, this is yet again a proof of the timeless axiom: assumption is the mother of all fuckups


Comment