I had a conversation with Stephen Toub, Peter Ritchie and Kevin Hazzard about the different between the TaskCancelledException and the OperationCancelledException. It turns out not to be a big difference, but some understanding might keep you out of a bit of trouble.
TaskCancelledException derives from OperationCancelledException. TaskCancelledException contains a property for the cancelled task.
If you’re catching exceptions, you probably want to catch both exceptions. If you don’t care about the task, you can do this by just catching the OperationCancelledException since the TaskCancelledException derives from it. Or you can catch them both in order if you use the task in your exception response. Catching only the TaskCancelledException will not work in all cases, since it won’t catch OperationCancelledException.
If you’re throwing an exception, and there’s a task available, throw TaskCanceledException. If there isn’t a task available, throw an OperationCancelledException. This is reflected in the framework when the CancellationToken’s ThrowIfCancellationRequested method throws an OperationCancelledException.
If you’re manually throwing cancellation exceptions, check that you aren’t repeating things already handled well by the .NET framework. CancellationTokenSource and CancellationToken may take a little getting used to, but this mechanism provides a predictable approach that handles some tricky threading side cases that will ultimately make your code simpler and easier to understand.
Read more: Leaning Into Windows
QR: