Question

How to catch exceptions from a ThreadPool.QueueUserWorkItem?

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

 45  21597  45
1 Jan 1970

Solution

 72

You can add try/catch like this:

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

Solution

 25

If you have access to action's source code, insert a try/catch block in that method; otherwise, create a new tryAction method which wraps the call to action in a try/catch block.

2009-04-15