I have a process set up to execute on background thread. I'm trying to make sure we handle the IIS process shutting down correctly but the CancellationToken doesn't seem to be working. For testing, I have this in the code run by the background thread:
while (!cancellationToken.IsCancellationRequested)
System.Threading.Thread.Sleep(1000);
cancellationToken.ThrowIfCancellationRequested();
...
catch (System.OperationCanceledException ex)
{
string message = String.Format("The background thread cancelled while copying a page because the application was shutting down. " +
"The page may have been copied to some locations prior to cancellation, but the task did not complete. RelativeUrl: {0}", relativeUrl);
_logger.Error(ex, message);
...
}
The problem is my log never gets the log entry. I've tried attaching the debugger with a breakpoint on the line containing ThrowIfCancellationRequested
and one in the catch block, then recycling the app pool. My breakpoints were never hit, the worker process ended and the VS debugger detached. Have I misunderstood or misused the cancellation token?
Edit
Here's how I start the task:
HostingEnvironment.QueueBackgroundWorkItem(c => processor.CopyPage(relativeUrl, overwrite, subPages, c));
I updated the code above to this and tried again:
while (true)
{
System.Threading.Thread.Sleep(1000);
cancellationToken.ThrowIfCancellationRequested();
}
This time I performed an iisreset. I continued stepping through the loop in the VS debugger after starting the iisreset. IsCancellationRequested remained false and an exception never appeared to be thrown. What's interesting is CancellationToken.CanBeCancelled is set to false. The docs for this property state:
If CanBeCanceled returns false, it is guaranteed that the token will never transition into a canceled state, meaning that IsCancellationRequested will never return true.