Reputation: 3650
As I know, if there's unhandled exception in task, and if you don't handle TaskScheduler.UnobservedTaskException, it will error later when it gets collected/finalized, and will kill your process.(I should emphasize that it is in .net4.0. I know we can suppress the unhandled exception in .net4.5 by default.)
This means that if I use the TaskScheduler.UnobservedTaskException, the application can be survived? I tested below code:
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += (o, ev) =>
{
Console.WriteLine(ev.Exception);
Console.WriteLine("---------");
};
for (int i = 0; i < 10; i++)
{
try
{
var t = Task.Factory.StartNew<int>(() =>
{ throw new Exception("xxxxxx"); return 1; },
CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
catch
{
Console.WriteLine("error");
}
}
while (true)
{
GC.Collect();
Thread.Sleep(1000);
}
Console.ReadKey();
}
This code creates 10 tasks and each task throws an unhandled exception. And the UnobservedTaskException is triggered once. Then the application is broken. (I tried to create only one task, in this case the application isn't broken.)
So my conclusion is that using the UnobservedTaskException event is not useful, process still can be killed. Am I right??
Upvotes: 2
Views: 1693
Reputation: 149538
You need to call UnobservedTaskExceptionEventArgs.SetObserved
to make it an observed exception:
TaskScheduler.UnobservedTaskException += (o, ev) =>
{
Console.WriteLine(ev.Exception);
Console.WriteLine("---------");
ev.SetObserved();
};
Upvotes: 3