且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在单个 catch 块中处理来自工作线程和主线程的异常?

更新时间:2022-12-15 20:16:24

第一个想法似乎是在它自己的线程中记录每个异常.

First idea seems to be to log every single exception in it's own thread.

无论如何,如果您需要跟踪多个异常,请考虑使用 AggregateException 类.

Anyway, if you need to keep track of multiple exception, consider using AggregateException class.

代替变量 MainThreadException,您可以保留一个 Listm_AllExceptions(或者更好,一个 SynchronizedCollection,因为您将从多个线程访问它)然后在主线程中检查异常时,您可以使用以下内容:

Instead of your variable MainThreadException, you can keep a List<Exception> m_AllExceptions (or better, a SynchronizedCollection<Exception>, since you will access it from multiple threads) and then when checking exception in the main thread you can use something such:

if (m_AllExceptions.Count > 0 != null)
{
    AggregateException ex = new AggregateException(m_AllExceptions);
    throw ex;
}