C # ThreadPool QueueUserWorkItem Exception Handling

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

+6
multithreading c # exception-handling
source share
2 answers

Best practice is that your background threads should not throw exceptions. Let them cope with their exceptions.

Ideally, you should wrap the code in your method, which is executed in the thread in the try-catch block and handle the exception in the catch block. Do not throw it from the catch block.

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

If you want to update the user interface from a background thread, you can do this using the Control.InvokeRequired and Control.Invoke property . For more information, see MSDN Links.

+4
source share

Unable to pass exception from thread to another. What you can do is create a synchronization mechanism to transfer information about exceptions between threads, and then output a new exception from the target thread something like this:

class Program { Exception _savedException = null; AutoResetEvent _exceptionEvent = new AutoResetEvent(false); static void Main(string[] args) { Program program = new Program(); program.RunMain(); } void RunMain() { ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod)); while (true) { _exceptionEvent.WaitOne(); if (_savedException != null) { throw _savedException; } } } void ThreadMethod(object contxt) { try { // do something that can throw an exception } catch (Exception ex) { _savedException = ex; _exceptionEvent.Set(); } } } 

If you have a Win Form application, things are much simpler. In the catch clause of your stream, use the Invoke (or BeginInvoke) method of your form, providing it with exception information. In a method launched with Invoke, you can restore or handle your exception as you wish.

+4
source share

All Articles