带有未处理异常的任务在瞄准.net 4.0时不会被拆除

本文关键字:0时 net 异常 未处理 任务 | 更新日期: 2023-09-27 18:13:27

根据http://blogs.msdn.com/b/pfxteam/archive/2009/05/31/9674669.aspx,有异常的任务应该拆除应用程序。

然而,在任务未处理的异常中,可接受的答案指出,在。net 4.5中,行为被更改为不拆除应用程序,我试图在MSVS 2013中重现崩溃行为,我无法让应用程序在瞄准。net 4.5时崩溃(这是预期的),但即使当我瞄准。net 4.0时,应用程序仍然在我通过弱引用检查任务不再存活后继续运行。

 class Program
{
    private static WeakReference _ThrowingExceptionOnATaskRun()
    {
        Task t = Task.Factory.StartNew(() =>
        {
            Console.WriteLine("Throwing exception in a task!");
            throw new NotImplementedException("Not implemented");
        });
        return new WeakReference(t);
    }
    static void MyMain()
    {
        Console.WriteLine("Main start");
        WeakReference weakReference = _ThrowingExceptionOnATaskRun();
        CheckIfAlliveForceGc(weakReference);
        CheckIfAlliveForceGc(weakReference);
        CheckIfAlliveForceGc(weakReference);
        CheckIfAlliveForceGc(weakReference);
        Console.WriteLine("Enter something:");
        string userInput = Console.ReadLine();
        Console.WriteLine("You entered : {0}", userInput);
        Console.WriteLine("Done...");
        Console.Read();
    }
    private static void CheckIfAlliveForceGc(WeakReference weakReference)
    {
        Console.WriteLine("Is reference alive : {0}", weakReference.IsAlive);
        Thread.Sleep(2000);
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
    static void Main(string[] args)
    {
        MyMain();
    }
}

输出
Main start
Is reference alive : True
Throwing exception in a task!
Is reference alive : False
Is reference alive : False
Is reference alive : False
Enter something:
hello
You entered : hello
Done...

带有未处理异常的任务在瞄准.net 4.0时不会被拆除

你需要在你的app/web中添加一个config元素。配置以保持旧的行为:

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