简体   繁体   中英

exception handling on background threads using Thread pool

The application I am working on uses thread pool. Here's the basic pseudo code.

On 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.

The "Component.GetObject" will basically return a CLR object using Yield return. This object needs to be processed by two other components on threads. So we are invoking the thread pool providing the call back method (that will invoke the two components).

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

Based on my reading, one of the approaches would be have a "flag" variable on the main thread. If there is an exception on the spawned thread, the thread would set the variable using locking mechanism. The parent thread would check the "flag" variable before spawning new threads.

I would like to know if there is a better approach for handling this scenario. Thread pool is being used since it manages the queueing of threads if the "for" loop spawns more threads than the thread pool limit.

I think the standard way is to just throw the exception and let the code that handles the thread pool handle it. Is this not possible in your implementation?

Even if the exception is handled, nothing is stopping you from throwing one into your 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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM