如何从 ThreadPool.QueueUserWorkItem 捕获异常?
我有以下引发异常的代码:
ThreadPool.QueueUserWorkItem(state => action());
当操作引发异常时,我的程序崩溃。 处理这种情况的最佳做法是什么?
I have the following code that throws an exception:
ThreadPool.QueueUserWorkItem(state => action());
When the action throws an exception, my program crashes. What is the best practice for handling this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以像这样添加 try/catch:
You can add try/catch like this:
如果您有权访问
action
的源代码,请在该方法中插入一个 try/catch 块; 否则,创建一个新的tryAction
方法,它将对action
的调用包装在 try/catch 块中。If you have access to
action
's source code, insert a try/catch block in that method; otherwise, create a newtryAction
method which wraps the call toaction
in a try/catch block.如果您使用 .Net 4.0,可能值得研究 Task 类,因为它可以为您处理这个问题。
与原始代码等效,但使用任务,看起来像
要处理异常,您可以向 StartNew 返回的任务添加延续。 它可能看起来像这样:
If you're using .Net 4.0, it might be worth investigating the Task class because it can take care of this for you.
The equivalent of your original code, but using Tasks, looks like
To deal with exceptions you can add a continuation to the Task returned by StartNew. It might look like this:
在另一个线程上,(在您“排队”的方法中,添加一个 try catch 子句...。然后在 catch 中,将捕获的异常放入共享的 Exception 变量(对主线程可见)中。
然后在您的主线程,当所有排队项目完成时(为此使用等待句柄数组)检查是否某个线程用异常填充了该共享异常...如果是,则重新抛出它或适当处理它...
这是一些示例代码在最近的一个项目中,我用它来...
HasException 是共享布尔值...
On the other thread, (in the method you are "queueing" up, add a try catch clause... .Then in the catch, place the caught exception into a shared Exception variable (visible to the main thread).
Then in your main thread, when all queued items have finished (use a wait handle array for this) Check if some thread populated that shared exception with an exception... If it did, rethrow it or handle it as appropriate...
here's some sample code from a recent project I used this for...
HasException is shared boolean...
我通常做的是在 action() 方法内创建一个大的 try ... catch 块
然后将异常存储为私有变量,然后在主线程中处理它
What I usually do is to create a big try ... catch block inside the action() method
then store the exception as a private variable then handle it inside the main thread
简单代码:
Simple Code: