What is the use of CancellationToken
\'s IsCancellationRequested
property? Consider below code
static void Main(string[] args)
{
The problem with your code is that you don't wait for the Task
to finish. So, what can happen is this:
Cancel()
.Status
, which returns Running
.Task
is still running.Main()
completes, application exits.IsCancellationRequested
would be checked from the background thread. But that never happens, since the application already exited.)To fix that, add t.Wait()
after you call Cancel()
.
But that still won't fix your program completely. You need to tell the Task
that it was canceled. And you do that by throwing OperationCanceledException
that contains the CancellationToken
(the usual way to do that is to call ThrowIfCancellationRequested()
).
One issue with that is that Wait()
ing on a Task
that was canceled will throw an exception, so you will have to catch that.