C#多线程Thread的Interrupt方法

发表于2018-08-09
评论0 72浏览

想免费获取内部独家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");
            }
        }
    }

原文链接

著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

标签:

游戏学院公众号二维码
腾讯游戏学院
微信公众号

提供更专业的游戏知识学习平台