本文實例講述了C#信號量用法。分享給大家供大家參考,具體如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;/* * 標題:如何使用信號量的示例代碼 * Author:kagula * Date:2015-6-16 * Environment:VS2010SP1, .NET Framework 4 client profile, C#. * Note:[1]“信號量”可以看成是“授權(證)池”。 * 一個授權(證)池內有零個或多個授權(證)。 * [2]下面的示例sem of Semaphore相當于最多只能有一個授權(證)的授權池。 * [3]每調用一次sem.Release添加一個授權(證)。 * 連接調用多次sem.Release導致超出授權池所能容納的授權(證)數量,會拋出異常。 * [4]每調用一次sem.WaitOne就使用一個授權(證)。 * */namespace kagula{ class mySemaphore { //第一個參數,代表當前授權次數。 // 0表示沒有授權(證)。 //第二個參數,代表Semaphore實例最多能容納幾個授權證。 // 1表示最大授權次數為1次。 // 超出允許的授權次數,比如說sem.Release連續調用了兩次,會拋出異常。 public static Semaphore sem = new Semaphore(0, 1); public static void Main() { //添加一次授權。 //釋放一個sem.WaitOne()的阻塞。 sem.Release(); myThread mythrd1 = new myThread("Thrd #1"); myThread mythrd2 = new myThread("Thrd #2"); myThread mythrd3 = new myThread("Thrd #3"); myThread mythrd4 = new myThread("Thrd #4"); mythrd1.thrd.Join(); mythrd2.thrd.Join(); mythrd3.thrd.Join(); mythrd4.thrd.Join(); //input any key to continue... Console.ReadKey(); }//end main function }//end main class class myThread { public Thread thrd; public myThread(string name) { thrd = new Thread(this.run); thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name + "正在等待一個許可(證)……"); //如果不加參數會導致無限等待。 if (mySemaphore.sem.WaitOne(1000)) { Console.WriteLine(thrd.Name + "申請到許可(證)……"); Thread.Sleep(500); //雖然下面添加了許可,但是,其它線程可能沒拿到許可,超時退出了。 Console.WriteLine(thrd.Name + "添加一個許可(證)……"); mySemaphore.sem.Release(); } else { Console.WriteLine(thrd.Name + " 超時(等了一段時間還是沒拿到許可(證))退出……"); } } }//end class}//end namespace希望本文所述對大家C#程序設計有所幫助。
|
新聞熱點
疑難解答