C#執行緒範例:Abort()方法


在C#中,Thread類的Abort()方法用於終止執行緒。如果未完成中止操作,它會引發ThreadAbortException異常。

using System;
using System.Threading;
public class MyThread
{
    public void Thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(i);
            Thread.Sleep(200);
        }
    }
}
public class ThreadExample
{
    public static void Main()
    {
        Console.WriteLine("Start of Main");
        MyThread mt = new MyThread();
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));

        t1.Start();
        t2.Start();
        try
        {
            t1.Abort();
            t2.Abort();
        }
        catch (ThreadAbortException tae)
        {
            Console.WriteLine(tae.ToString());
        }
        Console.WriteLine("End of Main");
    }
}

執行上面範例程式碼,得到以下結果(輸出是不可預測的,因為執行緒可能處於執行狀態。) -

Start of Main
0
End of Main