Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 518
Michael Hedgpeth Avatar asked Apr 15 '09 21:04

Michael Hedgpeth


People also ask

When should you not use Threadpool?

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.

What is the use of Threadpool QueueUserWorkItem method?

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.


1 Answers

You can add try/catch like this:

        ThreadPool.QueueUserWorkItem(state =>                                          {                                              try                                              {                                                  action();                                              }                                              catch (Exception ex)                                              {                                                  OnException(ex);                                              }                                          }); 
like image 55
Prankster Avatar answered Oct 18 '22 00:10

Prankster