rottenapple

博客园 首页 新随笔 联系 订阅 管理

上网搜索了一下,发现大家都提到了一个方法,使用Mutex类,但是其中有个问题很多人没有遇到。
就是如果项目文件很大的话,Mutex 对象在编译的时候可能会被当成垃圾给释放掉。
[STAThread]
    static void Main()                  // args are OK here, of course
    {
        bool ok;
        m = new System.Threading.Mutex(true, "YourNameHere", out ok);

        if (! ok)
        {
            MessageBox.Show("Another instance is already running.");
            return;
        }

        Application.Run(new Form1());   // or whatever was there

        GC.KeepAlive(m);                // important!
    }


其中GC.KeepAlive()必须有,原因如下:
We want the program to keep hold of the mutex as long as it's running. But the JIT compiler sees that the mutex is only used near the beginning of the program, and may discard it prematurely when memory is needed for something else!

posted on 2005-08-05 17:25  rottenapple  阅读(1281)  评论(4编辑  收藏  举报