//뮤텍스 생성
Mutex m = new Mutex();
//뮤텍스를 획득할 때까지 대기
m.WaitOne();
//뮤텍스 해제
m.ReleaseMutext();
아래는 머신에서 오직 한 프로세스만 사용하기 위한 예제이다. 머신 전체적으로 한 프로세스만 뜨게 하귀해, 고유의 Mutex명을 체크할 필요가 있는데, 이를 위해 GUID ( Globally Unique Idenrtifier)를 사용하였다. 처음 프로세스가 먼저 Mutex를 획득한 후에는, 그 프로세스가 죽기 전에는 머신 전체적으로 다른 프로세스가 Mutex를 획득할 수 없다는 점을 이요하여 잠시 (1초) 체크해 보고 이미 다른 프로세스가 Mutex를 가지고 있으면, 프로세스를 중단시키다.
using System;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
// GUID를 뮤텍스명으로 사용
//string mtxName = "4AD31D94-659B-44A7-9277-1DD793E415D1";
// GUID 대신 사용자 임의대로 뮤텍스 이름 사용
string mtxName = "Metashower";
Mutex mtx = new Mutex(true, mtxName);
// 1초 동안 뮤텍스를 획득하려 대기
TimeSpan tsWait = new TimeSpan(0, 0, 1);
bool success = mtx.WaitOne(tsWait);
// 실패하면 프로그램 종료
if (!success)
{
MessageBox.Show("이미실행중입니다.");
return;
}
// 성공하면 폼 실행
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
static void Main()
{
bool bnew;
Mutex mutex = new Mutex(true, "MutexName", out bnew);
if(bnew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
mutex.ReleaseMutex();
}
else
{
MessageBox.Show("프로그램이 실행중입니다.");
Application.Exit();
}
}
[C#] 프로퍼티 (0) | 2023.07.25 |
---|---|
[Factory Method Pattern] 팩토리 메서드 패턴 C# (0) | 2023.07.25 |
[C#] 동적 컴파일 (0) | 2023.07.18 |
.NET Serialization 닷넷 객체직렬화 (0) | 2023.07.18 |
[C#] Nullable<T> (0) | 2023.07.18 |