views:

104

answers:

1

I'm looking at the TPL exception handling example from MSDN @

http://msdn.microsoft.com/en-us/library/dd537614(v=VS.100).aspx

The basic form of the code is:

Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); });
try
{
   task1.Wait();
}
catch (AggregateException ae)
{
   throw ae.Flatten();
}

My question is: Is this a race condition? What happens if task1 throws before the try has executed? Am I missing something that stops this being a race?

Shouldn't it be written like this instead:

try
{
   Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); });
   task1.Wait();
}
catch (AggregateException ae)
{
   throw ae.Flatten();
}
+3  A: 

No, the first example is perfectly valid.

When the exception is raised in the Task it is wrapped in an AggregateException. Only when another thread joins the task, in this example by calling task1.Wait() is the exception propogated to the joining thread. Essentially the exception is 'stored' until it can be propogated back to a thread that is waiting for the feedback.

Chris Taylor