LoginSignup
1
3

More than 3 years have passed since last update.

【C#】Mutexクラスを使ったプログラムの排他制御

Posted at

はじめに

アプリケーションの多重起動を阻止したい場合はMutexクラスを使用すれば良い。
Mutexクラスを使うことで簡単に排他処理を作ることができる。

サンプルプログラム

Program.cs
using System;
using System.Diagnostics;

class Program
{
    private static System.Threading.Mutex _Mutex;

    static void Main(string[] args)
    {
        if(MutexTest())
        {
            Console.WriteLine("True 多重起動です。");
        }
        else
        {
            Console.WriteLine("false 単体起動です。");
        }

        Console.ReadKey();
    }

    static bool MutexTest()
    {
        //ミューテックスクラスのインスタンス生成
        _Mutex = new System.Threading.Mutex(false,"SubProcess");

        //Mutexの所有権を要求
        if (_Mutex.WaitOne(0, false) == false)
            return true;

        //プロセスを取得
        string AppName = Process.GetCurrentProcess().MainModule.FileName;
        var ps = Process.GetProcessesByName(AppName);

        bool ProcessFlg = false;

        foreach (var item in ps)
        {
            ProcessFlg = true;
            break;
        }

        //起動済ならreturn
        if (ProcessFlg)
            return true;

        return false;
    }
}

出力結果(単体でプログラムを起動の場合)

false 単体起動です。

出力結果(同プログラムを複数起動の場合、2つ目以降)

True 多重起動です。

ちなみに、プログラム上でMutexクラスを解放する際はReleaseMutexメソッドを使用する。

_Mutex.ReleaseMutex();
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3