捕獲在不同線程中拋出的異常我的一個方法(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 關注
- 588 瀏覽
添加回答
舉報
0/150
提交
取消
