user1214135
user1214135

Reputation: 635

Does the Recommended Task Exception-Handling Code Synchronize the Task?

It looks like the pattern on MSDN for handling exceptions raised in a Task synchronizes the code. Here is the code from the MSDN page:

var task1 = Task.Factory.StartNew(() =>
{
    throw new MyCustomException("I'm bad, but not too bad!");
});    
try
{
    task1.Wait();
}
catch (AggregateException ae)
{
    // Code removed
}

The call task1.Wait(); causes the calling thread to block until task1 completes, right? If so, then I don't see a reason for using a Task at all, because whether the code is called synchronously or asynchronously using a Task, the calling thread will block until either the code is finished running or an exception is thrown.

Also, what would happen if task1 throws an exception before the calling code enters the try-catch block? If that is possible, the try-catch block will not catch the AggregateException.

What should I do if I want the calling thread to be notified of an exception raised in a Task? I don't think I should have to call task1.Wait(); in order to be notified of an exception. I know about ContinueWith() but the code in ContinueWith() runs in a separate thread as well, not the calling thread.

Upvotes: 0

Views: 188

Answers (1)

Nick Hill
Nick Hill

Reputation: 4927

The call task1.Wait(); causes the calling thread to block until task1 completes, right? If so, then I don't see a reason for using a Task at all, because whether the code is called synchronously or asynchronously using a Task, the calling thread will block until either the code is finished running or an exception is thrown.

Right. But you can do whatever you need (e.g. start other tasks or perform some operations) on the calling thread before you call the Wait() method.

Also, what would happen if task1 throws an exception before the calling code enters the try-catch block? If that is possible, the try-catch block will not catch the AggregateException.

The exception will be caught and stored internally. Then, when you call the Wait() method on a task instance, the original exception will be wrapped in AggregateException and propagated to the calling thread.

Upvotes: 3

Related Questions