捕获在不同线程中抛出的异常我的一个方法(Method1)产生一个新线程。该线程执行一个方法(Method2),并在exectution期间抛出异常。我需要获取有关调用方法的异常信息(Method1)在某种程度上,我可以捕获这个Method1被抛出的异常Method2吗?
3 回答
子衿沉夜
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) { ... }这是代码的直接粘贴。对于其他用途,我建议提供一个动作或函数作为参数,并在线程上调用它而不是硬编码被调用的方法。
- 3 回答
- 0 关注
- 601 浏览
添加回答
举报
0/150
提交
取消
