C# FAQ: How ensure that only one instance of an application will run

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How ensure that only one instance of an application will run?

Often, it is necessary to be sure that only a single instance of an application will be running at a time. Examples include applications which control resources. There is a design pattern designed specifically for this purpose called the Singleton design pattern.

Another way of accomplishing this is by using a named mutex. The following example illustrates the creation of a mutex:

bool instantiated;
 
Mutex mutex = new Mutex
   (false, "Local\\" + aUniqueID, out instantiated);
 
// If instantiated is true, this is the first instance 
// of the application; else, another instance is running. 

The mutex must be local—meaning it exists in the current user session. If the mutex were not local, users could share the mutex. Thus, two different users could not be running the program at the same time. Unlike various examples to be found on the Web, this sample code does not contain a call to a ReleaseMutex method. Because, the mutex will be released automatically when the process dies. If this is not the desired behavior, add such a method.

The mutex will not be garbage collected. Therefore, if a local variable is only used near the beginning of a method, the Garbage Collector (GC) may ignore it when determining which variables are garbage collection "roots" if that part of the method has already been executed. This can result in the mutex being released earlier than expected. To prevent premature release, make a call to:

GC.KeepAlive (mutex);

at the end of the Main method.

Or, use a static variable to hold the mutex. That ensures that the mutex will not be garbage collected until the AppDomain is unloaded. With this strategy, even should the Main terminate, there will not be any problems if other threads are running.

Another strategy is to "listen" on a local port. Since only one process can listen to a particular port, this fact can be exploited to ensure that only one instance of your application is running. But, there will be problems if another application tries to use that port for any purpose. Also, this strategy provides a communication channel between the initial instance and the new instance. For example, the new instance might want to tell the initial instance to open a user-requested file. This could be accomplished using the socket.


See also


Personal tools