Related to this question, what is the best practice for naming a mutex? I realize this may vary with OS and even with version (esp for Windows), so please specify platform in answering. My interest is in Win XP and Vista.
A really safe name for a global mutex is <a description> + <a GUID>
:
MyApp Single Instance Mutex : {c96f7db4-d743-4718-bef0-8533a198bcca}
By using a name like this there is absolutely no chance someone else will use the same mutex name as your mutex.
Sniffing around with process explorer, you can see that GUIDs are used in a few places, though in general they are not used. A pattern that does emerge though is that the word "mutex" is used quite a lot and Microsoft seem to like using capitols.
Suggestion:
Incorporate the object type (Mutex in this case) and application Namespace into the unique name. This will generally be safe. If you want to really be safe then append a Guid as well.
Example:
string mutexName = "MUTEX: Skyz.Messaging.ThreadPooling.MyAppSingleInstance";
Advantages:
By creating a naming convention for your apps you make it easy to manage many object names, create more readable code and will make it very easy for existing and future developers to understand the code.
Tip:
Instead of using a Mutex Directly in your code write a reusable wrapper class that can make the code more maintainable in case you ever want to change the implementation or add a tweak. Remember to Remove the Mutex using a disposable pattern or you will have issues!
using (SingletonProcess singletonProcess = new SingletonProcess("MUTEX: Skyz.Apps.MessagingQueue.InstanceMarker"))
{
if (singletonProcess.IsDuplicateInstance)
{
ConsoleWriter.WriteColorLine("An instance of the ExporterService exists, you cannot start a second instance.");
return
}
A google search of CreateMutex samples reveals that "MyMutex" is the most common mutex name chosen.
Therefore you should name your mutex "NotMyMutex" to guarantee uniqueness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With