Aks Aks - 1 month ago 8
C# Question

C# ThreadPool QueueUserWorkItem Exception Handling

Whenever a thread in my ThreadPool throws an exception, my code seems to be stuck at the catch block inside the thread function. How do I get the exception back to the main thread?

Answer

The best practice is that your background threads should not throw exceptions. Let them handle their exceptions on their own.

Ideally you should wrap the code in your method that executes on a thread in a try-catch block and handle the exception in the catch block. Do not re-throw it from the catch block.

Read this for more details. http://www.albahari.com/threading/#_Exception_Handling

If you want to update the UI from background thread you can do that by using Control.InvokeRequired property and Control.Invoke method. See the MSDN links for details and examples.

Comments