何时在调用线程中引发 fire and forget Tasks 的异常?

When do exceptions from fire and forget Tasks get raised in the calling thread?

根据MSDN

If you do not wait on a task that propagates an exception, or access its Exception property, the exception is escalated according to the .NET exception policy when the task is garbage-collected. When exceptions are allowed to bubble up back to the joining thread, then it is possible that a task may continue to process some items after the exception is raised.

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

long collectionCount = 0;

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

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

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