【问题标题】:When do exceptions from fire and forget Tasks get raised in the calling thread?什么时候在调用线程中引发火灾和遗忘任务的异常?
【发布时间】:2017-03-08 19:39:45
【问题描述】:

根据MSDN

如果您不等待传播异常的任务,或者访问 它的 Exception 属性,异常是根据 垃圾收集任务时的 .NET 异常策略。什么时候 允许异常冒泡回到加入线程,然后 一个任务可能会在之后继续处理某些项目 引发异常。

我假设 Task 类有一个引发异常或其他东西的终结器。但是为什么以下似乎无限期运行?

long collectionCount = 0;

Task.Factory.StartNew(() => { throw new NotImplementedException(); });

while (true)
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    ++collectionCount;
}

【问题讨论】:

    标签: .net exception exception-handling .net-4.0 task-parallel-library


    【解决方案1】:

    从 .Net Framework 4.5 开始,unobserved exceptions from Tasks no longer crash the process when they are finalized。这意味着您的代码在 .Net 4.5(或更高版本)上运行,因此您将获得新的、非崩溃的行为。

    【讨论】:

    • 但我使用的是 Visual Studio 2010,并且项目属性中的目标框架设置为 .NET Framework 4 Client Profile。
    • 没关系。重要的是实际使用哪个框架来运行程序。
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多