如何在单个 catch 块中处理来自工作线程和主线程的异常? [英] How do I handle exceptions from worker threads and main thread in a single catch block?

查看:49
本文介绍了如何在单个 catch 块中处理来自工作线程和主线程的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 15 个工作线程同时运行.代码在 SSIS 包内运行,我必须保持主线程运行,直到所有工作线程成功完成或因错误而终止.

I have 15 worker threads running concurrently. The code runs inside SSIS package and I have to keep the main thread running until all the worker threads have successfully completed or terminated with error.

为了从工作线程中捕获异常,我有一个静态异常

To catch the exception from the worker thread I have a static Exception

static Exception Main_Exception = null;

由工作线程更新.

catch (Exception ex)
          {
            Main_Exception = ex;
          }

main 方法检查 Main_Exception 是否仍为 null 或已更新.

The main method check the Main_Exception is still null or has been updated.

if (Main_Exception != null)
                        {... }

对于出现的任何异常,我需要将异常详细信息插入到错误日志中.我想管理main方法的catch块中的所有异常.

For any exceptions arising I need to insert the exception-details into an error-log. I want to manage all the exceptions in the catch block of main method.

我设计了下面的主要方法.这种方法是正确的还是我错过了什么?在这种情况下,throw Main_Exception"或throw"是否能正常工作?

I have designed the main method below. Is the approach correct or am I missing out on something? Is "throw Main_Exception " OR "throw" going to work fine in this scenario?

main()
{
  try{
         if (Main_Exception != null)
            {
              throw  Main_Exception; OR throw;
            }
  }
  catch(Exception ex){
        //INSERT exception-details into error-log
  }
}

推荐答案

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

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;
}

这篇关于如何在单个 catch 块中处理来自工作线程和主线程的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆