C#多線程開發5:線程的Abort和Interrupt方法

來源:互聯網
上載者:User

標籤:abort   interrupt   多線程開發   threadabortexception   threadinterruptedexc   

使用線程的Abort方法可以終止線程;而使用線程的Interrupt方法只可以中斷處於 WaitSleepJoin 狀態的線程,當線程狀態不再為 WaitSleepJoin時,線程將恢複執行。線上程上調用Abort方法會引發 ThreadAbortException異常,調用Interrupt方法則會引發ThreadInterruptedException異常。

下面的執行個體示範了Abort和Interrupt方法的使用。

using System;using System.Threading; namespace AbortAndInterruptExp{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("------------Interrupt方法執行情況---------------");            Thread t1 = new Thread(DoWork);            t1.Start();            Thread.Sleep(1000);            t1.Interrupt();             t1.Join();             Console.WriteLine("------------Abort方法執行情況---------------");            Thread t2 = new Thread(DoWork);            t2.Start();            Thread.Sleep(1000);            t2.Abort();        }         static void DoWork()        {            for (int i = 0; i < 10; i++)            {                try                {                    Console.WriteLine("第" + i + "迴圈。");                    Thread.Sleep(500);                }                catch (ThreadInterruptedException e)                {                    Console.WriteLine("第" + i + "迴圈中,線程被中斷,下次迴圈線程將繼續運行。");                }                catch (ThreadAbortException e)                {                    Console.WriteLine("第" + i + "迴圈中,線程被終止,線程將不再繼續運行");                }            }        }    }}

執行個體結果如下所示。

 

從結果可以看出,當線程狀態為WaitSleepJoin 時,使用Interrupt方法可以中斷線程,當線程狀態不再為為WaitSleepJoin 時,線程將繼續執行;而Abort方法終止後的線程將不再執行。

C#多線程開發5:線程的Abort和Interrupt方法

聯繫我們

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