Background thread exception handling using thread pool

The application I'm working in uses a thread pool. Here is the basic pseudo code.

In the main thread

foreach(Object obj in Component.GetObject()) { //Invoke the thread pool providing the call back (method to be called on the background// thread) and pass the object as the parameter. } //Wait for the threads to complete. 

"Component.GetObject" will basically return a CLR object using Return. This object must be handled by two other components in the threads. Therefore, we call the thread pool, which provides a callback method (which will call the two components).

If there is an exception in the / s spawned thread, the parent thread must be notified so that it can break out of the for loop (that is, stop unwrapping more threads), wait for the spawned threads to complete, and then handle the exception.

Based on my reading, one approach would have a flag variable in the main thread. If there is an exception in the spawned thread, the thread will set the variable using the lock mechanism. The parent thread will check the flag variable until new threads arrive.

I would like to know if there is a better approach to handle this scenario. The thread pool is used because it manages the thread queue if the for loop generates more threads than the thread pool limit.

+4
source share
1 answer

I think the standard way is to simply throw an exception and let the code processing the thread pool handle it. Is this impossible in your implementation?

Even if an exception is handled, nothing prevents you from throwing it into the main thread from one of the other threads.

 //thread code try{ //something } catch (IOException e){ //handle your exception //and then throw another one, that you can catch later throw new ThreadFailedException() } 
0
source

Source: https://habr.com/ru/post/1309415/


All Articles