0评论

C#多线程Thread的Interrupt方法

文章来自CSDN博客 2018-08-09 5浏览

想免费获取内部独家PPT资料库?观看行业大牛直播?点击加入腾讯游戏学院游戏开发行业精英群711501594

上一篇给大家介绍了使用线程的Abort方法可以终止线程;而使用线程的Interrupt方法只可以中断处于 WaitSleepJoin 状态的线程,当线程状态不再为 WaitSleepJoin时,线程将恢复执行。

调用Interrupt方法会产生ThreadInterruptException异常
    class Program
    {
        static void Main(string[] args)
        {
            StayAwake stayAwake = new StayAwake();
            Thread newThread = new Thread(new ThreadStart(stayAwake.ThreadMethod));
            newThread.Start();
            newThread.Name = "new thread";
            newThread.Interrupt();
            Console.WriteLine("main thread calls interrupt on new thread");
            stayAwake.SleepSwitch = true;
            Console.WriteLine("1stat " + Thread.CurrentThread.ThreadState);
            newThread.Join();
        }
    }
    class StayAwake
    {
        bool sleepSwitch = false;
        public bool SleepSwitch
        {
            set
            {
                sleepSwitch = value;
            }
        }
        public void ThreadMethod()
        {
            Console.WriteLine("new thread is executing thread method");
            while (!sleepSwitch)
            {
                Thread.SpinWait(10000000);
            }
            try
            {
                Console.WriteLine("2name " + Thread.CurrentThread.Name);
                Console.WriteLine("2stat " + Thread.CurrentThread.ThreadState);
                Console.WriteLine("new thread going to sleep");
                Thread.Sleep(Timeout.Infinite);
            }
            catch (ThreadInterruptedException e)
            {
                Console.WriteLine("new thread can not go to sleep -" + "interrupted by main thread");
            }
        }
    }