WinCE5.0移動平台開發筆記(.Net主線程撲捉子線程中的異常)

來源:互聯網
上載者:User

     首先看一段C#代碼:運行後發現主線程通過try{}catch{}是不能撲捉子線程中的拋出來的異常。

代碼

 class Program
    {
        static void Main(string[] args)
        {
            try
            {
                System.Threading.Thread thread = new System.Threading.Thread(new Program().run);
                thread.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Thread.Sleep(1000);
        }
        public void run()
        {
            throw new Exception();
        }
    }

 

為什麼呢?

首先需要瞭解異常的實現機制:異常的實現機制是嚴重依賴與線程的棧的。每個線程都有一個棧,線程啟動後會在棧上安裝一些異常處理幀,並形成一個鏈表的結構,在異常發生時通過該鏈表可以進行棧復原,如果你自己沒有安裝的話,可能會直接跳到鏈表尾部,那可能是CRT提供的一個預設處理幀,彈出一個對話方塊提示某某地址記憶體錯誤等,然後確認調試,取消關閉。

所以說,線程之間是不可能發生異常處理的交換關係的。

但是在實際的程式設計中,會牽涉到撲捉子線程的異常,那麼該怎樣解決這個問題呢?

代碼

    class Program
    {
        private delegate void ExceptionHandler(Exception ex);
        private static ExceptionHandler exception;
        private static void ProcessException(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        static void Main(string[] args)
        {
            exception = new ExceptionHandler(ProcessException);
            System.Threading.Thread thread = new System.Threading.Thread(new Program().run);
            thread.Start();

            Thread.Sleep(1000);
        }
        public void run()
        {
            try
            {
                throw new Exception();
            }
            catch (Exception ex)
            {
                if (exception != null)
                {
                    exception(ex);
                }
            }
        }
    }

 

上面使用委託的方式,間接的解決了:把子線程中的異常資訊交個主線程的一個方法去執行。(通過委託方式)

 

Best Reagrds,

Charles Chen

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.