使用线程池对后台线程进行异常处理

时间:2010-05-11 12:05:55

标签: c# multithreading exception exception-handling pool

我正在处理的应用程序使用线程池。这是基本的伪代码。

在主线程上

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”基本上将使用Yield return返回CLR对象。此对象需要由线程上的两个其他组件处理。所以我们调用提供回调方法的线程池(将调用这两个组件)。

如果生成的线程有异常,则需要通知父线程,以便它可以突破for循环(即停止生成更多线程),等待生成的线程完成然后处理例外。

根据我的阅读,其中一种方法是在主线程上有一个“标志”变量。如果生成的线程有异常,则线程将使用锁定机制设置变量。父线程将在生成新线程之前检查“flag”变量。

我想知道是否有更好的方法来处理这种情况。正在使用线程池,因为如果“for”循环产生的线程多于线程池限制,它会管理线程的排队。

1 个答案:

答案 0 :(得分:0)

我认为标准方法是抛出异常并让处理线程池的代码处理它。这在您的实施中是不可能的吗?

即使处理了异常,也没有什么能阻止你从一个其他线程中将一个抛入主线程。

//thread code
try{
    //something
}
catch (IOException e){
    //handle your exception

    //and then throw another one, that you can catch later
    throw new ThreadFailedException()
}
相关问题