I have the following code that throws an exception:
ThreadPool.QueueUserWorkItem(state => action());   When the action throws an exception, my program crashes. What is the best practice for handling this situation?
Related: Exceptions on .Net ThreadPool Threads
Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline.
QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.
You can add try/catch like this:
        ThreadPool.QueueUserWorkItem(state =>                                          {                                              try                                              {                                                  action();                                              }                                              catch (Exception ex)                                              {                                                  OnException(ex);                                              }                                          }); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With