C#線程隊列用法實例剖析。本站提示廣大學習愛好者:(C#線程隊列用法實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是C#線程隊列用法實例剖析正文
本文實例講述了C#線程隊列用法。分享給年夜家供年夜家參考。詳細以下:
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ThreadPro { class Program { static Mutex gM1; static Mutex gM2; const int ITERS = 100; static AutoResetEvent Event1 = new AutoResetEvent(false); static AutoResetEvent Event2 = new AutoResetEvent(false); static AutoResetEvent Event3 = new AutoResetEvent(false); static AutoResetEvent Event4 = new AutoResetEvent(false); static void Main(string[] args) { Console.WriteLine("Mutex Sample "); //創立一個Mutex對象,而且定名為MyMutex gM1 = new Mutex(true, "MyMutex"); //創立一個未定名的Mutex 對象. gM2 = new Mutex(true); Console.WriteLine(" - Main Owns gM1 and gM2"); AutoResetEvent[] evs = new AutoResetEvent[4]; evs[0] = Event1; //為前面的線程t1,t2,t3,t4界說AutoResetEvent對象 evs[1] = Event2; Program tm = new Program(); Thread t1 = new Thread(new ThreadStart(tm.t1Start)); Thread t2 = new Thread(new ThreadStart(tm.t2Start)); Thread t3 = new Thread(new ThreadStart(tm.t3Start)); Thread t4 = new Thread(new ThreadStart(tm.t4Start)); t1.Start();// 應用Mutex.WaitAll()辦法期待一個Mutex數組中的對象全體被釋放 t2.Start();// 應用Mutex.WaitOne()辦法期待gM1的釋放 t3.Start();// 應用Mutex.WaitAny()辦法期待一個Mutex數組中隨意率性一個對象被釋放 t4.Start();// 應用Mutex.WaitOne()辦法期待gM2的釋放 Thread.Sleep(2000); Console.WriteLine(" - Main releases gM1"); gM1.ReleaseMutex(); //線程t2,t3停止前提滿 Thread.Sleep(1000); Console.WriteLine(" - Main releases gM2"); gM2.ReleaseMutex(); //線程t1,t4停止前提知足 //期待一切四個線程停止 WaitHandle.WaitAll(evs); Console.WriteLine(" Mutex Sample"); Console.ReadLine(); } public void t1Start() { Console.WriteLine("辦法一運轉, Mutex.WaitAll(Mutex[])"); Mutex[] gMs = new Mutex[2]; gMs[0] = gM1;//創立一個Mutex數組作為Mutex.WaitAll()辦法的參數 gMs[1] = gM2; Mutex.WaitAll(gMs);//期待gM1和gM2都被釋放 gM1.ReleaseMutex(); //修改上一次湧現的毛病 gM2.ReleaseMutex(); //修改上一次湧現的毛病 Thread.Sleep(2000); Console.WriteLine("辦法一終了,WaitAll(Mutex[]) satisfied"); Event1.Set(); //線程停止,將Event1設置為有旌旗燈號狀況 } public void t2Start() { Console.WriteLine("辦法二運轉, gM1.WaitOne( )"); gM1.WaitOne();//期待gM1的釋放 gM1.ReleaseMutex(); //修改上一次湧現的毛病 Console.WriteLine("辦法二終了, gM1.WaitOne( ) satisfied"); Event2.Set();//線程停止,將Event2設置為有旌旗燈號狀況 } public void t3Start() { Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])"); Mutex[] gMs = new Mutex[2]; gMs[0] = gM1;//創立一個Mutex數組作為Mutex.WaitAny()辦法的參數 gMs[1] = gM2; Mutex.WaitAny(gMs);//期待數組中隨意率性一個Mutex對象被釋放 gM1.ReleaseMutex(); //修改上一次湧現的毛病 Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])"); Event3.Set();//線程停止,將Event3設置為有旌旗燈號狀況 } public void t4Start() { Console.WriteLine("t4Start started, gM2.WaitOne( )"); gM2.WaitOne();//期待gM2被釋放 gM2.ReleaseMutex(); //修改上一次湧現的毛病 Console.WriteLine("t4Start finished, gM2.WaitOne( )"); Event4.Set();//線程停止,將Event4設置為有旌旗燈號狀況 } } }
願望本文所述對年夜家的C#法式設計有所贊助。