C#Thread的Interrupt方法

本文通过一个具体的示例代码详细介绍了在.NET环境下如何使用Interrupt方法来中断处于WaitSleepJoin状态的线程,并解释了该方法如何抛出ThreadInterruptException异常。此外还探讨了线程在不同状态下对中断信号的响应方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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");
            }
        }
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值