How to catch exceptions from a ThreadPool.QueueUserWorkItem?

Michael Hedgpeth picture Michael Hedgpeth · Apr 15, 2009 · Viewed 19.5k times · Source

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

Answer

Prankster picture Prankster · Apr 15, 2009

You can add try/catch like this:

        ThreadPool.QueueUserWorkItem(state =>
                                         {
                                             try
                                             {
                                                 action();
                                             }
                                             catch (Exception ex)
                                             {
                                                 OnException(ex);
                                             }
                                         });