C#子線程的異常處理)

來源:互聯網
上載者:User

http://www.cnblogs.com/lwolf/archive/2010/04/19/1715712.html

前幾天在修改記賬程式,把匯入資料的那部分改了一下,改為用線程操作,這樣匯入資料多的時候主介面不會出現假死狀態。
      在 原來的代碼裡面有一些try{}catch{}的異常處理代碼,在加入子線程的時候這些代碼也留著,想通過throw把異常拋出到主線程來。在測試時發 現,子線程無法將異常拋出給主線程,程式報錯了。於是上網查了些資料,得知線程之間是不可能發生異 常處理的交換關係的。
      所以解決辦法就是用委託來處理子線程的異常
      定義如下委託

代碼

        private delegate void ChildThreadExceptionHandler(string message);
        private event ChildThreadExceptionHandler ChildThreadException;
        protected virtual void OnChildThreadException(string message)
        {
            if (ChildThreadException != null)
                ChildThreadException(message);
        }

 

      在 線程啟動前綁定事件

代碼

                ChildThreadException = null;
                ChildThreadException += new ChildThreadExceptionHandler(Import_ChildThreadException);

                Thread thread = new Thread(ImportThreadMethod);
                thread.Start();

      在 子線程出現異常的地方調用OnChildThreadException(ex.Message)就可以了。

      Import_ChildThreadException 就是具體的處理異常的方法了,彈出對話方塊或是什麼別的就看你的需求了。

 

轉自:http://www.lwolf.cn/blog/article/code/csharp-thread-exception.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.