System.Threading.Mutex :同步基元,它只向一個執行緒授予對共用資源的獨佔訪問權。[MSDN]

實現原理: 在程式啟動時,請求一個互斥體,如果能獲取對指定互斥的訪問權,就繼續運行程式,否則就退出程式。
測試代碼: 

class Test

     {

         /// <summary>

         /// 應用程式的主入口點。

         /// </summary>

          [STAThread]

         static void Main(string[] args)

         {

              bool flag=false;

              System.Threading.Mutex mutex=new System.Threading.Mutex(true,"Test",out flag);

              //第一個參數:true--給調用執行緒賦予互斥體的初始所屬權

              //第一個參數:互斥體的名稱

              //第三個參數:返回值,如果調用執行緒已被授予互斥體的初始所屬權,則返回true

              if(flag)

              {

                   Console.Write("Running");

              }

              else

              {

                   Console.Write("Another is Running");

                   System.Threading.Thread.Sleep(5000);//執行緒掛起5秒鐘

           //請勿使用this.close(); 會有錯誤發生

                   Environment.Exit(1);//退出程式

              }

              Console.ReadLine();

         }


運行結果:
第一次運行,輸出"Running"
不關閉第一次運行的程式, 進行第二次運行,輸出"Another is Running",五秒鐘後,程式自動退出。

 

arrow
arrow
    全站熱搜

    狼翔月影 發表在 痞客邦 留言(0) 人氣()