问题
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:
- Handle the exception in the thread, gather the information you need to log and save it.
- 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