[轉MSDN]C# Thread.Abort

Some people says that Thread.Abort is evil.But the following is what the msdn says.


http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx

using System;
using System.Threading;
using System.Security.Permissions;

public class ThreadWork {
    public static void DoWork() {
        try {
            for(int i=0; i<100; i++) {
                Console.WriteLine("Thread - working."); 
                Thread.Sleep(100);
            }
        }
        catch(ThreadAbortException e) {
            Console.WriteLine("Thread - caught ThreadAbortException - resetting.");
            Console.WriteLine("Exception message: {0}", e.Message);
            Thread.ResetAbort();
        }
        Console.WriteLine("Thread - still alive and working."); 
        Thread.Sleep(1000);
        Console.WriteLine("Thread - finished working.");
    }
}

class ThreadAbortTest {
    public static void Main() {
        ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
        Thread myThread = new Thread(myThreadDelegate);
        myThread.Start();
        Thread.Sleep(100);
        Console.WriteLine("Main - aborting my thread.");
        myThread.Abort();
        myThread.Join();
        Console.WriteLine("Main ending."); 
    }
}
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章