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?
Asked
Active
Viewed 1.7k times
107

Rob Hruska
- 118,520
- 32
- 167
- 192

Peter
- 1,685
- 3
- 16
- 22
1 Answers
125
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".

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
1I came up with a ForEachAsync mostly from Stephen Toub's blog https://blogs.msdn.microsoft.com/pfxteam/2012/03/05/implementing-a-simple-foreachasync-part-2/ . Then if I throw an exception inside an `await enumerable.ForEachAsync( async () => { throw new ApplicationException( "Test" ); } );` somehow it is 'changed' to a TaskCanceledException. Any idea how that might be? This is problem for me as I want to catch a 'true' OperationCanceledException via catch ( OperationCanceledException ) but I don't want this TaskCanceledException (which should really be ApplicationException) caught. – Terry Oct 23 '16 at 19:17