【问题标题】:Task with unhandled exception not tearing down while targetting .NET 4.0以 .NET 4.0 为目标时未处理未处理异常的任务
【发布时间】:2014-07-17 19:33:33
【问题描述】:

根据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...

【问题讨论】:

    标签: c# multithreading task


    【解决方案1】:

    您需要在 app/web.config 中添加一个配置元素以保留旧行为:

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

    【讨论】:

      猜你喜欢
      • 2011-12-20
      • 2014-03-06
      • 1970-01-01
      • 2023-03-30
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多