Starting a new task inside a function can crash a program?
I have a function that is called by several GUI components, and always needs to be run in a different Task. Is there a differen开发者_开发技巧ce between doing it in this way each time:
public int foo()
{
// do what you need to do
return 1;
}
...
var t = Task<int>.Factory.StartNew(() =>foo());
and starting the task inside the foo function?
public int foo()
{
var t = Task<int>.Factory.StartNew(() =>
{
// do what you need to do
return 1;
});
}
...
foo();
I get System.AggregateException
in this program, and I'm starting to think that the second way to start the task is a wrong one.
Have a look at the InnerException. The AggregateException
is used to bundle up exceptions caused by Tasks/PLinq. More info here:
http://msdn.microsoft.com/en-us/library/system.aggregateexception.aspx
AggregateException is used to consolidate multiple failures into a single, throwable exception object. It is used extensively in the Task Parallel Library and Parallel LINQ (PLINQ). For an example, see How to: Handle Exceptions Thrown by Tasks and How to: Handle Exceptions in a PLINQ Query.
Worth also reading How to: Handle Exceptions Thrown by Tasks
精彩评论