亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

捕獲在不同線程中拋出的異常

捕獲在不同線程中拋出的異常

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 關注
  • 585 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號