【发布时间】: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