不得不感叹一下天下代码一大抄,到百度上一搜,结果都是如下的代码。
[STAThread]
static void Main()
{
//只允许运行一个程序
bool createNew;
System.Threading.Mutex mutex = new System.Threading.Mutex
(true, "Global\\" + Application.ProductName, out createNew);
{
if (createNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
MessageBox.Show("只允许运行一个程序!");
}
}
}
恐怕大家找到的和这大同小异,很可惜,这段代码DEBUG模式下没问题,在RELEASE却没有成功,
问题原因是Mutex被声明为一个局部变量,在relese模式下由于优化问题,可能由于编译器认为Mutex不再被
使用,被回收了,正确的代码如下,本人测试过
static System.Threading.Mutex mutex;
[STAThread]
static void Main()
{
//只允许运行一个程序
bool createNew;
mutex = new System.Threading.Mutex
(true, "Global\\" + Application.ProductName, out createNew);
{
if (createNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
MessageBox.Show("只允许运行一个程序!");
}
}
}