1. 程式人生 > 實用技巧 >C# 執行緒學習記錄

C# 執行緒學習記錄

1. 執行緒的建立,啟動,暫停,恢復和中止;

Thread th = new Thread(ThreadMethod);  // 建立執行緒
        static void ThreadMethod()
        {
            while(true)
            {
                Console.WriteLine("Thread executing......\n");
                Thread.Sleep(1000);
            }
        }
        static void Main(string
[] args) { Console.WriteLine("Main start...\n"); Thread th = new Thread(ThreadMethod); // 建立執行緒 th.Start(); // 啟動執行緒 for (int i = 0; i < 10; i++) { if (i == 3) th.Suspend(); // 掛起執行緒 if
(i == 5) th.Resume(); // 繼續執行緒 if (i == 7) th.Abort(); // 中止執行緒 Console.WriteLine(i + "\n"); Thread.Sleep(1000); } Console.WriteLine("Main end \n"); Console.ReadLine(); }

Suspend 和Resume 提示如下資訊:

修復該提示,新增一個 AutoResetEvent,修改程式碼如下:

class Program
    {
        private static bool State = true;
        static AutoResetEvent ResetThr = new AutoResetEvent(false);

        public static void Stop()
        {
            State = false;
        }
        public static void Continue()
        {
            State = true;
            ResetThr.Set();
        }
        public static void Add()
        {
            while (true)
            {
                for (int i = 0; i < 1000; i++)
                {
                    if (!State)
                    {
                        ResetThr.WaitOne();
                        //// to suspend thread.
                        //ResetThr.Reset();
                    }
                    if(i==20)
                    {
                        Stop();
                        Console.WriteLine("Stop thread");
                    }
                    Console.WriteLine(i);
                    Thread.Sleep(500);
                    i++;
                }
            }
        }
        static void ThreadMethod()
        {
            while(true)
            {
                if (!State)
                {
                    Thread.Sleep(3000);
                    Continue();
                    Console.WriteLine("Resume thread");
                }
                Console.WriteLine("Thread executing......");
                Thread.Sleep(1000);
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Main start...");
            Thread th = new Thread(ThreadMethod);  // 建立執行緒
            Thread th2 = new Thread(Add);
            th2.Start();
            th.Start();    // 啟動執行緒
            Console.WriteLine("Main end");
            Console.ReadLine();
        }
    }