本文介绍了使用线程池对后台线程进行异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在主线程上

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

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

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

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 (i.e. stop spawing more threads), wait for the spawned threads to complete and then handle the exception.

基于我的阅读,其中一个方法将在主线程上有一个标志变量。如果产生的线程有异常,线程将使用锁定机制设置变量。父线程会在产生新线程之前检查flag变量。

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.

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

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.

推荐答案

p>我认为标准的方法是抛出异常,让处理线程池的代码处理它。这是不可能的在您的实现?

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?

即使处理异常,没有什么阻止你从其他线程之一投掷到主线程。 p>

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()
}

这篇关于使用线程池对后台线程进行异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:45