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.
问题:
回答1:
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.
回答2:
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
}
回答3:
You could combine a description of what you're protecting against with the word "Guard"
回答4:
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.
回答5:
I haven't used GUID's in the past, but I'm starting to think its a good idea - if you think about all the developers in the world working of different software.
Unless you are thinking up quite obscure names that you can be assured are unique, you should think about GUID's.