日期:2014-05-18  浏览次数:20835 次

这个在release版本里不起作用!郁闷
C# code

bool flag = false;
            Process current = Process.GetCurrentProcess();
            System.Threading.Mutex mutex = new System.Threading.Mutex(true, current.ProcessName, out  flag);
            if (flag)
            {
                try
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }
                catch
                {
                    Application.Exit();
                }
            }
            else
            {
                Application.Exit();
                return;
            }


------解决方案--------------------
你的Mutex被垃圾回收了。

解决方法一:把mutex定义到方法外面,以便保持一个引用,防止被回收。
解决方法二:在Main方法的最后一行调用mutex.Dispose(); 同样是延长mutex的生命,防止被过早回收。

C# code

static System.Threading.Mutex mutex;       //<--

void static Main()
{
    bool flag = false;
    Process current = Process.GetCurrentProcess();
    mutex = new System.Threading.Mutex(true, current.ProcessName, out  flag);       //<---
    if (flag)
    ...