Introduction
Sometimes you'd want to limit your application to a single instance. In Win32
we had the CreateMutex
API function using which we could create a named
mutex and if the call failed, we assume that the application is already running.
Well the .NET SDK gives us the Mutex
class for
inter-thread/inter-process synchronization. Anyway in this article we are more interested in using the
Mutex
class to limit our apps to a single instance rather than in its use
as an inter-process data synchronization object.
The Class
The code below is nothing new. It's simply a .NET version of a universal
technique that has been used pretty much successfully over the years. For a
thorough understanding of this technique and other techniques and issues
involved when making single instance applications, you must read Joseph M
Newcomer's article -
Avoiding Multiple Instances of an Application
__gc class CSingleInstance
{
private:
Mutex *m_mutex;
public:
CSingleInstance(String *mutexname)
{
m_mutex=new Mutex(false,mutexname);
}
~CSingleInstance()
{
m_mutex->ReleaseMutex ();
}
bool IsRunning()
{
return !m_mutex->WaitOne(10,true);
}
};
Using it in your program
int __stdcall WinMain()
{
CSingleInstance *si=
new CSingleInstance("{94374E65-7166-4fde-ABBD-4E943E70E8E8}");
if(si->IsRunning())
MessageBox::Show("Already running...so exiting!");
else
Application::Run(new MainForm());
return 0;
}
Remember to put the following line on top of your program.
using namespace System::Threading;
I have used the string {94374E65-7166-4fde-ABBD-4E943E70E8E8}
as my unique mutex name. You can use
a name that you believe will be unique to your application. Using a GUID would
be the smartest option obviously. You can put the
class in a DLL and thus you can use it from all your applications.
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.
Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.
Nish's Technology Blog :
voidnish.wordpress.com