Mutexを使用して、アプリケーションの単一のインスタンスを実行します.

1255 ワード

http://www.dotblogs.com.tw/jjnnykimo/archive/2009/05/07/8328.aspx
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」を出力します.最初の運転のプログラムを閉じません. 2回目の運転を行い、「Another」を出力します. is Running「5秒後、プログラムは自動的に終了します.