if (thread.ThreadState = ThreadState.Running) { thread.Suspend(); } f.恢復線程
用來恢復已經掛起的線程,以讓它繼續執行,如果線程沒掛起,也不會起作用。
if (thread.ThreadState = ThreadState.Suspended) { thread.Resume(); } 下面將列出一個例子,以說明簡單的線程處理功能。此例子來自於幫助文檔。
using System; using System.Threading; // Simple threading scenario: Start a static method running // on a second thread. public class ThreadExample { // The ThreadProc method is called when the thread starts. // It loops ten times, writing to the console and yIElding // the rest of its time slice each time, and then ends. public static void ThreadProc() { for (int i = 0; i < 10; i++) { Console.WriteLine("ThreadProc: {0}", i); // YIEld the rest of the time slice. Thread.Sleep(0); } }
public static void Main() { Console.WriteLine("Main thread: Start a second thread."); // The constructor for the Thread class requires a ThreadStart // delegate that represents the method to be executed on the // thread. C# simplifIEs the creation of this delegate. Thread t = new Thread(new ThreadStart(ThreadProc)); // Start ThreadProc. On a uniprocessor, the thread does not get // any processor time until the main thread yIElds. Uncomment // the Thread.Sleep that follows t.Start() to see the difference. t.Start(); //Thread.Sleep(0);
for (int i = 0; i < 4; i++) { Console.WriteLine("Main thread: Do some work."); Thread.Sleep(0); }
Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends."); t.Join(); Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program."); Console.ReadLine(); } } 此代碼產生的輸出類似如下內容:
Main thread: Start a second thread. Main thread: Do some work. ThreadProc: 0 Main thread: Do some work. ThreadProc: 1 Main thread: Do some work. ThreadProc: 2 Main thread: Do some work. ThreadProc: 3 Main thread: Call Join(), to wait until ThreadProc ends. ThreadProc: 4 ThreadProc: 5 ThreadProc: 6 ThreadProc: 7 ThreadProc: 8 ThreadProc: 9 Main thread: ThreadProc.Join has returned. Press Enter to end program.