c#中我们可以使用System.Threading.Thread类来创建并启动一个线程,例子如下

Thread thread = new Thread(new ThreadStart(Execute1));
thread.Start(); 
public void Execute1()
{       
   Thread.Sleep(10000); 
}

Thread类通过ThreadState变量来代表线程当前的状态。 ThreadState是一个带flag特性的枚举变量,因此判断线程当前的状态,必须使用bitmask。作为一个特例,由于Running状态的bit码是0,因此,需要用如下方式判断线程是否处于运行状态:(thread.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0


  • 线程状态值

System.Threading.ThreadState(enum):

ThreadState
Summary
Running=0 The thread has been started, it is not blocked, and there is no pending System.Threading.ThreadAbortException
StopRequested = 1 The thread is being requested to stop. This is for internal use only.
SuspendRequested = 2 The thread is being requested to suspend.
Background = 4

The thread is being executed as a background thread, as opposed to a foreground thread. This state is controlled by setting the System.Thread

ing.Thread.IsBackground property.

Unstarted = 8 The System.Threading.Thread.Start() method has not been invoked on the thread.
Stopped = 16 The thread has stopped
WaitSleepJoin = 32 The thread is blocked. This could be the result of calling System.Threading.Thread.Sleep(System.Int32)  or System.Threading.Thread.Join(), of requesting a lock — for example, by  calling System.Threading.Monitor.Enter(System.Object) or System.Threading.Monitor.Wait(System.Object,System.Int32,System.Boolean)   — or of waiting on a thread synchronization object such as System.Threading.ManualResetEvent.
Suspended = 64 The thread has been suspended.
AbortRequested = 128 The System.Threading.Thread.Abort(System.Object) method has been invoked on the thread, but the thread has not yet received the pending System.Threading.ThreadAbortException  that will attempt to terminate it.
Aborted = 256 The thread state includes System.Threading.ThreadState.AbortRequested and the thread is now dead, but its state has not yet changed to System.Threading.ThreadState.Stopped.


  • 状态转换图

c# 线程状态及转换_第1张图片

  • Join线程

    当调用线程的Join()函数时,将会阻塞当前调用线程直到被Join线程结束,

    如果在调用Join()函数之前,该线程已经运行结束,当前调用线程不会被阻塞。

 

        public void Test4()
        {
            Thread thread1 = new Thread(new ThreadStart(Execute4_1));
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);
            thread1.Start();
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);
            thread1.Join();
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);
        }
        public void Execute4_1()
        {
            Console.WriteLine("Execute4_1 started");
            Thread.Sleep(10000);
            Console.WriteLine("Execute4_1 finished");
        }

控制台输出:

ThreadStatus1:Unstarted
ThreadStatus1:Running
Execute4_1 started
Execute4_1 finished
ThreadStatus1:Stopped


  • Abort线程

    当调用线程的Abort函数时,在线程内部将会触发一个System.Threading.ThreadAbortException,线程内部可以catch该异常来进行线程终结处理。


 

        object test5Lock = new object();
        Thread thread1 = null;
        Thread thread2 = null;
        public void Test5()
        {
            thread1 = new Thread(new ThreadStart(Execute5_1));
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);
            thread1.Start();
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);
            thread2 = new Thread(new ThreadStart(Execute5_2));
            Console.WriteLine("ThreadStatus2:" + thread1.ThreadState);
            thread2.Start();
            Console.WriteLine("ThreadStatus2:" + thread1.ThreadState);
        }
        public void Execute5_1()
        {
            try
            {
                while (true)
                {
                    Monitor.Enter(test5Lock);
                    Console.WriteLine("Execute5_1");
                }
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine("ThreadAbortException");
                Console.WriteLine(e.StackTrace);
            }
            catch (ThreadInterruptedException e)
            {
                Console.WriteLine("ThreadInterruptedException");
                Console.WriteLine(e.StackTrace);
            }
        }
        public void Execute5_2()
        {
            Thread.Sleep(5000);
            thread1.Abort("Test");
        }


控制台输出:

ThreadStatus1:Unstarted
ThreadStatus1:Running
ThreadStatus2:Unstarted
ThreadStatus2:Running
ThreadAbortException
   at System.Threading.Monitor.Enter(Object obj)
   at ThreadResearch.ThreadStatusTest.Execute5_1() in E:\MyWorkspace\Projects\CS
harpBasicLib\ThreadResearch\ThreadStatusTest.cs:line 145
ThreadStatus1:Aborted


  • Interrupt线程

    当被调用线程处于WaitSleepJoin状态时,调用Interrupt()函数,在线程内部将会抛出ThreadInterruptedException,否则什么事情也不会发生。


        object test5Lock = new object();
        Thread thread1 = null;
        Thread thread2 = null;
        public void Test5()
        {
            Thread thread3 = new Thread(new ThreadStart(Execute5_3));
            thread3.Start();
            Thread.Sleep(1000);

            thread1 = new Thread(new ThreadStart(Execute5_1));
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);
            thread1.Start();
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);

            thread2 = new Thread(new ThreadStart(Execute5_2));
            Console.WriteLine("ThreadStatus2:" + thread2.ThreadState);
            thread2.Start();
            Console.WriteLine("ThreadStatus2:" + thread2.ThreadState);

            thread1.Join();
            Console.WriteLine("ThreadStatus1:" + thread1.ThreadState);
        }


        public void Execute5_1()
        {
            try
            {
                while (true)
                {
                    Monitor.Enter(test5Lock);
                }
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine("ThreadAbortException");
                Console.WriteLine(e.StackTrace);
            }
            catch (ThreadInterruptedException e)
            {
                Console.WriteLine("ThreadInterruptedException");
                Console.WriteLine(e.StackTrace);
            }
        }

        public void Execute5_2()
        {
            Thread.Sleep(5000);
            thread1.Interrupt();
            //thread1.Abort("Test");
        }

        public void Execute5_3()
        {
            Monitor.Enter(test5Lock);
            Thread.Sleep(100000);
        }


控制台输出:

ThreadStatus1:Unstarted
ThreadStatus1:Running
ThreadStatus2:Unstarted
ThreadStatus2:Running
ThreadInterruptedException
   at System.Threading.Monitor.Enter(Object obj)
   at ThreadResearch.ThreadStatusTest.Execute5_1() in E:\MyWorkspace\Projects\CS
harpBasicLib\ThreadResearch\ThreadStatusTest.cs:line 149
ThreadStatus1:Stopped