Mutexクラスを使用できます。
- 特定の名前を持つ Mutex はシステムごとに常に1 つしか存在しない可能性があるため、アプリケーションの最初の起動時にインスタンス化できます。
- アプリケーションインスタンスがミューテックスを所有できるかどうかは、アプリケーションが開始されるたびに確認できます。
- そうでない場合は、アプリケーションの別のインスタンスが既に存在することがわかり、新しいインスタンスを適切に閉じることができます。
での作業Mutex
は非常に単純明快です。
using System;
using System.Threading;
public class Test
{
public static void Main()
{
// Set this variable to false if you do not want to request
// initial ownership of the named mutex.
bool requestInitialOwnership = true;
bool mutexWasCreated;
// Request initial ownership of the named mutex by passing
// true for the first parameter. Only one system object named
// "MyMutex" can exist; the local Mutex object represents
// this system object. If "MyMutex" is created by this call,
// then mutexWasCreated contains true; otherwise, it contains
// false.
Mutex m = new Mutex(requestInitialOwnership,
"MyMutex",
out mutexWasCreated);
// This thread owns the mutex only if it both requested
// initial ownership and created the named mutex. Otherwise,
// it can request the named mutex by calling WaitOne.
if (!(requestInitialOwnership && mutexWasCreated))
{
// The mutex is already owned by another application instance.
// Close gracefully.
// Put your exit code here...
// For WPF, this would be Application.Current.Shutdown();
// (Obviously, that would not work in this Console example.. :-) )
}
// Your application code here...
}
}