Difference between OperationCanceledException and TaskCanceledException?

C#ExceptionAsynchronousTask

C# Problem Overview


What is the difference between OperationCanceledException and TaskCanceledException? If I am using .NET 4.5 and using the async/await keywords, which one should I be looking to catch?

C# Solutions


Solution 1 - C#

OperationCanceledException is simply the base class for TaskCanceledException - so if you catch the former, you'll still catch the latter.

Some operations on concurrent collections throw just OperationCanceledException, as there aren't any actual tasks involved (at least as far as the public API is concerned). See BlockingCollection.TryTake for an example.

I would catch the OperationCanceledException just in case the task is cancelled due to an operation which itself just threw OperationCanceledException - you probably still want to treat that as "just cancellation".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow