开发者

MSDN Example of handling an exception from the TPL - Is this a race condition?

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 =开发者_如何学C 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();
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜