1 System.Threading.Mutex mutex = new System.Threading.Mutex(false, "SINGLE_INSTANCE_MUTEX");
2 if (!mutex.WaitOne(0, false)) //请求互斥的所有权
3 {
4 mutex.Close();
5 mutex = null;
6 }
7 if (mutex == null)
8 {
9 Console.WriteLine("已经有一个实例启动");
10 Console.ReadKey();
11 return;
12 //Environment.Exit(0);
13 }
2 if (!mutex.WaitOne(0, false)) //请求互斥的所有权
3 {
4 mutex.Close();
5 mutex = null;
6 }
7 if (mutex == null)
8 {
9 Console.WriteLine("已经有一个实例启动");
10 Console.ReadKey();
11 return;
12 //Environment.Exit(0);
13 }
结果:
打开一个应用程序,当打开第二应用程序的时候显示:已经有一个实例启动,打开第三个,第四个,...情况同打开第二个相同
不过,当打开第一个应用程序,后打开第二个应用程序,关闭第一个应用程序,打开第三个应用程序时,则不显示:已经有一个实例启动。
=================================================================================
使用下面方法可以解决此问题:
1 bool isRun;
2 System.Threading.Mutex mutex=new System.Threading.Mutex(true,"SINGLE_INSTANCE_MUTEX",out isRun);
3 if(!isRun)
4 {
5 Console.WriteLine("已经有一个实例启动");
6 Console.ReadKey();
7 return;
8 }
2 System.Threading.Mutex mutex=new System.Threading.Mutex(true,"SINGLE_INSTANCE_MUTEX",out isRun);
3 if(!isRun)
4 {
5 Console.WriteLine("已经有一个实例启动");
6 Console.ReadKey();
7 return;
8 }
=======================================================================================
1 System.Threading.Mutex mutex = new System.Threading.Mutex(false, "SINGLE_INSTANCE_MUTEX");
2 if (!mutex.WaitOne(0, false)) //请求互斥的所有权
3 {
4 mutex.Close();
5 mutex = null;
6 }
7 if (mutex == null)
8 {
9 Console.WriteLine("已经有一个实例启动");
10 Environment.Exit(0);
11 }
2 if (!mutex.WaitOne(0, false)) //请求互斥的所有权
3 {
4 mutex.Close();
5 mutex = null;
6 }
7 if (mutex == null)
8 {
9 Console.WriteLine("已经有一个实例启动");
10 Environment.Exit(0);
11 }
如果让应用程序强制退出的应该没问题。