简体   繁体   English

未处理的异常会中断应用程序吗?

[英]An unhandled exception breaks the application?

It is said in .net 4.0, an unhandled exception in task will make the application broken when it is finalized. 据说在.net 4.0中,任务中未处理的异常会使应用程序在完成时损坏。 (It is also said in .net 4.5, MS edits the exception rule that unhandled exception won't be thrown). (在.net 4.5中也有说,MS编辑了不会抛出未处理的异常的异常规则)。

But I tried below code, to see the appliction. 但是我尝试下面的代码,以查看该应用程序。 (in .net4.0), but it seems strong. (在.net4.0中),但看起来很强大。

static void Main(string[] args)
{

    for (int i = 0; i < 100; i++)
    {
        var t = Task.Factory.StartNew<int>(() => { throw new Exception("xxxxxx"); return 1; }
            , CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
    }

    while (true)
    {
        GC.Collect();
        Thread.Sleep(1000);
    }
    Console.ReadKey();
}

The code run the GC.Collect() to finalize the Task object, but the application is ok. 该代码运行GC.Collect()以完成Task对象,但该应用程序正常。 It isn't broken. 它没有坏。

Why? 为什么?

If you have .net 4.5 installed on your machine, that does an in place modification of .net 4.0 as well which may be why you are getting the behavior you are seeing. 如果您的计算机上安装了.net 4.5,那么它也会对.net 4.0进行就地修改,这可能就是您得到所看到的行为的原因。

If you want unobserved exceptions to still be thrown you can add the following section to your config file: 如果您仍然希望引发未观察到的异常,则可以将以下部分添加到配置文件中:

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

More info about <ThrowUnobservedTaskExceptions> . 有关<ThrowUnobservedTaskExceptions>更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM