In the .NET space there has been a lot of interest in things like async, await and TPL in the recent years. A very common issue is that someone expects cancellation to be one of these:
- immediate
- pre-emptive (as opposed to cooperative)
- as easy as the
Task.Run(..., cancellationToken)
API makes it seem - somehow built into
async/await
.
We need a canonical answer that explains...
- ...that cancellation is cooperative by nature
- ...how to achieve it when a cancellation token can be passed
- ...how to cancel when the API you are calling is not cooperating (e.g. by isolating and ignoring the still running action)
- ...common mistakes such as expecting
Task.Run(..., cancellationToken)
to always work - ...that
Thread.Abort
is not a solution although it appears to work.
Subjectively I think we have about 10 questions per week that require a rote answer to explain one of the points above. Here's the latest one. There are a lot of them in total with very few unique issues among them:
I did not find a good canonical that can be used to routinely close off cancellation questions.
Putting this here in case someone is interested in spending maybe 1 hour to create a comprehensive nice canonical answer. The goal should be to come to a place where we routinely close off these questions just like we do with NullReferenceException
. The canonical NullReferenceException
works excellently for this purpose.
by calling await on a Task or async method we are actually suspending that thread so it will block any successive code
is not accurate.await
releases the thread (kind of), it does not suspend it. Not trying to put down your experience but maybe this task is one notch above your current skill?! I can't know for sure.