安全地抛出在另一个线程上创建的异常C# [英] Safe to throw an exception created on another thread C#

查看:174
本文介绍了安全地抛出在另一个线程上创建的异常C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在线程A中捕获一个异常,然后将异常对象传递给线程B,并将其从线程B中抛出。这是否安全?



线程A

  try {
//引发异常的代码
} catch(异常e){
sendToOtherThread(e);
}

线程B

 异常e = receiveException(); 
throw e;

编辑



为了清楚起见:我了解线程是如何工作的,以及如何将对象引用从一个线程传递给另一个线程。更多的问题是从一个没有创建它的线程中抛出一个异常对象是安全的,或者是否存在类 Exception 本身或.NET处理方式的任何问题

解决方案

您可以重新抛出从另一个线程收到的异常(例如,在BackgroundWorker的RunWorkerCompleted事件处理程序),但是将它放在另一个异常中会更常见,以保留堆栈跟踪:

  private void backgroundWorker1_RunWorkerCompleted(
对象发件人,RunWorkerCompletedEventArgs e)
{
//首先,处理抛出异常的情况。
if(e.Error!= null)
{
throw new SomeException(... message ...,e.Error);
}
...
}


I want to catch an exception in a thread A, then pass the exception object to a thread B, and throw it from thread B. Is that safe?

Thread A

try {
    // Code that throws exceptions
} catch (Exception e) {
    sendToOtherThread(e);
}

Thread B

Exception e = receiveException();
throw e;

EDIT

For sake of clarity: I understand how threading works, and how I should pass the object reference from one thread to the other. The question is more about is it safe to throw an exception object from one thread that did not create it or is there any problem with the class Exception itself or the way .NET handles it.

解决方案

You can rethrow an exception received from another thread (for example, in a BackgroundWorker's RunWorkerCompleted event handler), but it would be more usual to wrap it in another exception, to preserve the stack trace:

private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    // First, handle the case where an exception was thrown.
    if (e.Error != null)
    {
        throw new SomeException("... message ...", e.Error);
    }
    ...
}

这篇关于安全地抛出在另一个线程上创建的异常C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆