c#多线程中(interrupt的实例使用)

c#多线程中(interrupt的实例使用)

我也不想说废话,直接copy代码去感受一下吧,童鞋!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadLine004
{
    class Program
    {
        public static Thread sleeper;
        public static Thread interrupter;

        static void SleepThread()
        {
            for (int i = 1; i <= 50; i++)
            {
                Console.Write(i+" ");
                if (i == 10 || i == 20 || i == 30)
                {
                    Console.WriteLine("在循环到{0}处进入休眠",i);
                    try
                    {
                        Thread.Sleep(1000);
                    }
                    catch
                    {
                        //这里还捕捉 因interrupt而引起的异常滴呀;
                    }
                }
            }
        }

        //这样操作,相当于sleeper 中无论怎么设置sleep() 中的参数,都没用滴呀;
        static void InterruptThread() 
        {
            while(1==1)
            {
                //一旦发现它“偷懒”,马上interrupt它“偷懒的状态”,然后继续干活 
                if (sleeper.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
                {
                    Console.WriteLine("中断睡眠状态<快起来工作>");
                    sleeper.Interrupt();
                    //它只能用于中断处于ThreadState.WaitSleepJoin状态的线程;
                    //并引发ThreadInterruptedException 的异常
                }
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("在主线程中启动了两个子线程;");

            sleeper = new Thread(new ThreadStart(SleepThread));
            interrupter = new Thread(new ThreadStart(InterruptThread));

            sleeper.Start();
            interrupter.Start();

        }
    }
}

让我们想象一下我们将一个线程设置了其长达1星期的睡眠时间,有时后必须唤醒它,上述方法就能实现这点 !

好吧,这里顺便记录一下我们的abort方法。

1.尝试对尚未启动的线程调用Abort

  如果对一个尚未启动的线程调用Abort的话,一旦该线程启动就被停止了

2.尝试对一个挂起的线程调用Abort

  如果在已挂起的线程上调用 Abort,则将在调用 Abort 的线程中引发 ThreadStateException,并将 AbortRequested 添加到被中止的线程的ThreadState 属性中。直到调用 Resume 后,才在挂起的线程中引发 ThreadAbortException。如果在正在执行非托管代码的托管线程上调用 Abort,则直到线程返回到托管代码才引发 ThreadAbortException。

 

原文地址:https://www.cnblogs.com/mc67/p/5109741.html