捕获在不同线程中抛出的异常

捕获在不同线程中抛出的异常

我的一个方法(Method1)产生一个新线程。该线程执行一个方法(Method2),并在exectution期间抛出异常。我需要获取有关调用方法的异常信息(Method1

在某种程度上,我可以捕获这个Method1被抛出的异常Method2吗?



白衣非少年
浏览 544回答 3
3回答

www说

您无法在Method1中捕获异常。但是,您可以捕获Method2中的异常并将其记录到原始执行线程随后可以读取和使用的变量中。

子衿沉夜

我有一个特殊的问题,我想从集成测试套件中使用包含控件的项目,因此必须创建一个STA线程。我最终得到的代码如下,放在这里以防其他人有相同的问题。    public Boolean? Dance(String name) {         // Already on an STA thread, so just go for it         if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) return DanceSTA(name);         // Local variable to hold the caught exception until the caller can rethrow         Exception lException = null;         Boolean? lResult = null;         // A gate to hold the calling thread until the called thread is done         var lGate = new ManualResetEvent(false);         var lThreadStart = new ThreadStart(() => {             try {                 lResult = DanceSTA(name);             } catch (Exception ex) {                 lException = ex;             }             lGate.Set();         });         var lThread = new Thread(lThreadStart);         lThread.SetApartmentState(ApartmentState.STA);         lThread.Start();         lGate.WaitOne();         if (lException != null) throw lException;         return lResult;     }     public Boolean? DanceSTA(String name) { ... }这是代码的直接粘贴。对于其他用途,我建议提供一个动作或函数作为参数,并在线程上调用它而不是硬编码被调用的方法。
打开App,查看更多内容
随时随地看视频慕课网APP