C#--检索线程状态

Thread对象的生存期特征由一组状态描述。Thread对象的ThreadState属性将返回下列10个数值中的一个:

  • Unstarted  线程尚未开始
  • Running   线程正则执行
  • Background  线程正在后台执行
  • WaitSleepJoin  线程由于调用Wait、Sleep或Join方法而被阻塞
  • SuspendRequested  线程对象位于当前挂起的进程中
  • Suspended  线程对象已经停止
  • StopRequested  线程对象位于当前停止的进程中
  • Stopped  线程对象已经停止
  • AbortRequested  Abort方位已被调用,但是线程对象尚未收到ThreadAbortException
  • Aborted  线程对象被异常终止

     Thread对象可以在某一时刻处于多种状态。例如,某个正在等待资源的Thread对象,如果在它等待时调用了Abort方法,那么该线程对象可能同时处于WaitSleepJoin和AbortRequested状态。


1 /*
2 Example14_3.cs illustrates the ThreadState property
3 */
4
5 using System;
6 using System.Threading;
7
8 class Example14_3
9 {
10
11 // the Countdown method counts down from 10 to 1
12 public static void Countdown()
13 {
14 for (int counter = 10; counter > 0; counter--)
15 {
16 Console.Write(counter.ToString() + " ");
17 }
18 Console.WriteLine();
19 }
20
21 // the DumpThreadState method displays the current Thread's state
22 // Note that ThreadState is a bitmask, and multiple states for the
23 // same thread are valid
24 public static void DumpThreadState (
25 Thread t
26 )
27 {
28 Console.Write("Current state: ");
29 if ((t.ThreadState & ThreadState.Aborted) == ThreadState.Aborted)
30 Console.Write("Aborted ");
31 if ((t.ThreadState & ThreadState.AbortRequested) ==
32 ThreadState.AbortRequested)
33 Console.Write("AbortRequested ");
34 if ((t.ThreadState & ThreadState.Background) ==
35 ThreadState.Background)
36 Console.Write("Background ");
37 if ((t.ThreadState &
38 (ThreadState.Stopped | ThreadState.Unstarted |
39 ThreadState.Aborted)) == 0)
40 Console.Write("Running ");
41 if ((t.ThreadState & ThreadState.Stopped) == ThreadState.Stopped)
42 Console.Write("Stopped ");
43 if ((t.ThreadState & ThreadState.StopRequested) ==
44 ThreadState.StopRequested)
45 Console.Write("StopRequested ");
46 if ((t.ThreadState & ThreadState.Suspended) ==
47 ThreadState.Suspended)
48 Console.Write("Suspended ");
49 if ((t.ThreadState & ThreadState.SuspendRequested) ==
50 ThreadState.SuspendRequested)
51 Console.Write("SuspendRequested ");
52 if ((t.ThreadState & ThreadState.Unstarted) ==
53 ThreadState.Unstarted)
54 Console.Write("Unstarted ");
55 if ((t.ThreadState & ThreadState.WaitSleepJoin) ==
56 ThreadState.WaitSleepJoin)
57 Console.Write("WaitSleepJoin ");
58 Console.WriteLine();
59 }
60
61 public static void Main()
62 {
63
64 // create a second thread
65 Thread t2 = new Thread(new ThreadStart(Countdown));
66 DumpThreadState(t2);
67
68 // launch the second thread
69 t2.Start();
70 DumpThreadState(t2);
71
72 // and meanwhile call the Countdown method from the first thread
73 Countdown();
74
75 // shut down the second thread
76 t2.Abort();
77 DumpThreadState(t2);
78
79 }
80
81 }
上一篇:《深入浅出DPDK》—第2章2.9节NUMA系统


下一篇:《MySQL DBA修炼之道》——2.3 其他MySQL分支的安装