非UI线程中运行时WinRT不报异常

WinRT does not report an exception when running in a non-UI thread

在一个线程中,我捕获了 ThreadCanceledException,但没有捕获到其他线程,希望能看到错误(如果有的话)。但是,当线程启动并且代码有错误时,它会产生消息

A first chance exception of type 'System.Exception' occurred in ...
The thread ... has exited with code 259 (0x103)

并在不显示实际异常的情况下优雅地退出。只有当我运行 UI线程中的代码才能识别错误。

有没有办法在线程中报告实际的异常?

您可以使用 TaskScheduler.UnobservedTaskException 事件跟踪这些异常:

TaskScheduler.UnobservedTaskException += (sender, eventArgs) =>
{
    Debug.WriteLine("Unobserved exception: {0}", eventArgs.Exception);
};

请注意,此事件不会立即触发,而是在垃圾收集器收集到故障任务后触发。那是因为创建任务的代码应该是观察异常的代码(例如通过调用 task.Wait()task.Result,或者通过等待它)。只有在运行时确定没有其他人可以观察到异常时才会触发该事件。