Mutex names - best practice?

瘦欲@ 提交于 2019-12-05 04:54:30
Sam Saffron

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  


            }

You could combine a description of what you're protecting against with the word "Guard"

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!