C# で二重起動を防止する方法。

名前付きミューテックスを生成し、WaitOne で取得できるかチェックするというもの。待ち時間なしでよい。アプリケーションのエントリポイントで行う。

static class Program
{
    [STAThread]
    static void Main()
    {
        // 二重起動防止
        using (Mutex mtx = new Mutex(false, Application.ProductName))
        {
            if (mtx.WaitOne(0, false))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());

                mtx.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("すでに起動されています。");
            }
            mtx.Close();
        }
    }
}