【问题标题】:UnobservedTaskException is not killing the processUnobservedTaskException 没有杀死进程
【发布时间】:2015-08-08 14:46:48
【问题描述】:

我试图了解 .NET 4.0 中的 UnobservedTaskException 问题,因此我编写了以下代码

TaskScheduler.UnobservedTaskException += (sender, eventArgs) => Console.WriteLine("unobserved");

Task.Factory.StartNew(() => { throw new Exception(); }, TaskCreationOptions.LongRunning);
using (var autoResetEvent = new AutoResetEvent(false))
{
    autoResetEvent.WaitOne(TimeSpan.FromSeconds(10));
}
Console.WriteLine("Collecting");
GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("Still working ");
Console.ReadKey();
Console.WriteLine("Still working ");
Console.WriteLine("Still working ");
Console.ReadKey();

UnobservedTaskException 被触发,然后我的应用程序继续工作。但是根据MSDN 应该杀死该进程。谁能告诉我为什么?

【问题讨论】:

  • 如何确保它在 .Net 4.0 上运行?

标签: c# .net-4.0 task-parallel-library task unobserved-exception


【解决方案1】:

如果您在仅安装了 .Net 4.0 的机器上运行此代码,它确实会崩溃。

由于自 4.0 以来的所有 .Net 版本都是就地更新,即使您将应用程序定位为 .Net 4.0,它也会在具有更新版本的机器上运行。

要在更高版本上运行时获得与 .Net 4.0 相同的行为,您可以将其添加到您的 app.config 文件中(如 TaskScheduler.UnobservedTaskException Event 中所述):

<runtime> 
    <ThrowUnobservedTaskExceptions enabled="true"/> 
</runtime> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多