Liny_@NotePad

沉迷ACG中

C#单实例运行Sample

YOYO posted @ 2010年9月03日 21:08 in 【C#】 with tags 内核对象 单实例 , 3056 阅读

之前在C++里接触过内核同步对象,早上在前辈的代码里看到了,于是用C#实现看看。

其实很简单,通过System.Threading.Mutex就可以直接管理了……

创建一个WinForm项目,之所以用WinForm是因为运行时比较明显 = =。。

创建一个单例类CommonClass:

using System.Threading;

namespace MutexTest
{
    public class CommonClass
    {
        private static CommonClass instance = new CommonClass();

        public static CommonClass Instance
        {
            get { return instance; }
        }

        private CommonClass() { }

        private Mutex mutex;

        public bool StartMutex()
        {
            bool flag = true;

            if (mutex == null)
            {
                mutex = new Mutex(false, mutexName, out flag);
            }

            return flag;
        }
    }
}

修改主程序内容为:

CommonClass tmpClass = CommonClass.Instance;
            if (tmpClass.StartMutex())
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经在运行另一实例!");
            }

这样即可实现单例运行。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter