I am trying to migrate to using the CancellationToken/Src constructs in .NET, e.g.: https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads
My basic question is in regards to reacting to a cancellation request.
In my case I have some long-running processing that is not important for consistency. When a cancellation request arrives, I can't afford the pattern of "polling", e.g.:
while (!_token.IsCancellationRequested)
{
DoProcessing(...)
}
Because the processing can take several minutes and I really want to exit right now.
My question is if the proper method is then to simply use this setup:
public void Start()
{
_token.Register(() => _token.ThrowIfCancellationRequested());
// Continuously process stuff.
while (!_token.IsCancellationRequested)
{
DoProcessing(...)
}
}
That is, register a callback which in turn just throws the OperationCanceledException.
I can read here: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.cancel?view=netframework-4.8 , that:
We recommend that cancelable operations and callbacks registered with CancellationToken not throw exceptions.
However...
What is the proper way of interrupting my processing immediately, rather than polling, and still adhering to the "rules" prescribed by the framework?