针对.NET 4.0目标的未处理异常任务未能撤销

3
根据此链接 http://blogs.msdn.com/b/pfxteam/archive/2009/05/31/9674669.aspx,具有未处理异常的任务应关闭该应用程序。
然而,在 Task unhandled exceptions 中 ,接受的答案指出在 .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...
1个回答

1

你需要在你的应用程序/网站的web.config中添加一个配置元素来保持旧的行为:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接