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

发布于 2024-09-01 14:27:46 字数 642 浏览 4 评论 0原文

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

在主线程上

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

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

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

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

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 (i.e. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南烟 2024-09-08 14:27:46

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

即使处理了异常,也没有什么可以阻止您从其他线程之一将异常抛出到主线程中。

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

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

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()
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文