Reputation: 7791
Recommended method of observing a cancellationToken cancellation request seems to be to ThrowIfCancellationRequested
.
But what happens if it is caught by user try-catch? From MSDN's "How to: Cancel a Task and Its Children" with try-catch added to illustrate question:
snippet:
static void DoSomeWork(int taskNum, CancellationToken ct)
{
try
{
for (int i = 0; i < maxIterations; i++)
{
// Do a bit of work. Not too much.
...
//ok not to do this check? most likely IsCancellationRequested does it already
//if (ct.IsCancellationRequested)
//{
ct.ThrowIfCancellationRequested();
//}
}
}
catch(OperationCanceledException e1) // catching likely my own exception
{
throw; // correct? anything else belongs here?
}
catch // ...
{
// do whatever else I might want to do here
}
}
Am I fine re-throwing? I.e. I am not disturbing anything inside the Task APIs, am I?
(I will also express the personal opinion, that the point of an orderly cancel-cleanup-return seems at odds with exception being the vehicle for it; I assume there are other means to accomplish that - I'll keep digging)
Upvotes: 4
Views: 648
Reputation: 2434
rethrow should be fine. But usage of parameterless catch is not recommended, as it swallows any exception info. You should use catch (Exception) and at least log these exceptions.
Upvotes: 2