为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
白衣非少年 2019-08-26 17:19:13
捕获在不同线程中抛出的异常我的一个方法(Method1)产生一个新线程。该线程执行一个方法(Method2),并在exectution期间抛出异常。我需要获取有关调用方法的异常信息(Method1)在某种程度上,我可以捕获这个Method1被抛出的异常Method2吗?
查看完整描述

3 回答

?
www说

TA贡献1775条经验 获得超8个赞

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


查看完整回答
反对 回复 2019-08-26
?
子衿沉夜

TA贡献1828条经验 获得超3个赞

我有一个特殊的问题,我想从集成测试套件中使用包含控件的项目,因此必须创建一个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) { ... }

这是代码的直接粘贴。对于其他用途,我建议提供一个动作或函数作为参数,并在线程上调用它而不是硬编码被调用的方法。


查看完整回答
反对 回复 2019-08-26
  • 3 回答
  • 0 关注
  • 543 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信