How do I handle exceptions from worker threads and main thread in a single catch block?

时光总嘲笑我的痴心妄想 提交于 2021-01-29 07:20:16

问题


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;

which is updated by the worker threads.

catch (Exception ex)
          {
            Main_Exception = ex;
          }

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

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

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.

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

回答1:


You can't manage exceptions thrown on the background worker thread in the main application.

You are going to have to handle them in the thread itself.

If you want all the logging to be in one place then you are going to have to do something like this:

  1. Handle the exception in the thread, gather the information you need to log and save it.
  2. In the code that monitors the thread (i.e. reacts to the thread events) read this error state and throw a new exception with the necessary information.

This will then be handled and logged in your global exception handler.




回答2:


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

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

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


来源:https://stackoverflow.com/questions/34222433/how-do-i-handle-exceptions-from-worker-threads-and-main-thread-in-a-single-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!