C# 執行緒中有時候會需要用到某一個執行緒等待另一個執行緒執行完或經過多久才能執行,MSDN裡面有個簡單透過console的範例,覺得滿受用並在此留下腳印囉....
using System;
using System.Threading;
public class SampleCode
using System;
using System.Threading;
public class SampleCode
{ static Thread mainThread, thread1, thread2; public static void Main() { mainThread = Thread.CurrentThread; thread1 = new Thread(ThreadProc); thread1.Name = "Thread1"; thread1.Start(); thread2 = new Thread(ThreadProc); thread2.Name = "Thread2"; thread2.Start(); } private static void ThreadProc() { Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name); if (Thread.CurrentThread.Name == "Thread1" && Thread2.ThreadState != ThreadState.Unstarted)
if (thread2.Join(2000)) // 超過兩秒 terminate!
Console.WriteLine("Thread2 has termminated.");
else
Console.WriteLine("The timeout has elapsed and Thread1 will resume.");
Thread.Sleep(4000); Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name); Console.WriteLine("Thread1: {0}", thread1.ThreadState); Console.WriteLine("Thread2: {0}\n", thread2.ThreadState); } }
留言
張貼留言