根据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...
答案 0 :(得分:1)
您需要在app / web.config中添加一个配置元素以保持旧行为:
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>