I have a windows application (C#) and i need to configure it to run one instance from the application at the time , It means that one user clicked the .exe file and the appl
I'd use a Mutex for this scenario. Alternatively, a Semaphore would also work (but a Mutex seems more apt).
Here's my example (from a WPF application, but the same principles should apply to other project types):
public partial class App : Application
{
const string AppId = "MY APP ID FOR THE MUTEX";
static Mutex mutex = new Mutex(false, AppId);
static bool mutexAccessed = false;
protected override void OnStartup(StartupEventArgs e)
{
try
{
if (mutex.WaitOne(0))
mutexAccessed = true;
}
catch (AbandonedMutexException)
{
//handle the rare case of an abandoned mutex
//in the case of my app this isn't a problem, and I can just continue
mutexAccessed = true;
}
if (mutexAccessed)
base.OnStartup(e);
else
Shutdown();
}
protected override void OnExit(ExitEventArgs e)
{
if (mutexAccessed)
mutex?.ReleaseMutex();
mutex?.Dispose();
mutex = null;
base.OnExit(e);
}
}