互斥体名称 - 最佳实践?
与此问题相关,命名互斥体的最佳实践是什么? 我意识到这可能会因操作系统甚至版本(尤其是 Windows)而异,因此请在回答时指定平台。 我的兴趣是Win XP 和Vista。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
全局互斥体的一个真正安全的名称是
+
:通过使用这样的名称,其他人绝对不可能使用与您的互斥体相同的互斥体名称。
使用进程资源管理器进行嗅探,您可以看到 GUID 在一些地方使用,但通常不会使用它们。 不过,确实出现的一种模式是“互斥体”这个词被大量使用,而微软似乎喜欢使用国会大厦。
A really safe name for a global mutex is
<a description> + <a GUID>
: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.
建议:
将对象类型(本例中为互斥体)和应用程序命名空间合并到唯一名称中。 这通常是安全的。 如果你想真正安全,那么还可以附加一个 Guid。
示例:
优点:
通过为应用程序创建命名约定,您可以轻松管理许多对象名称,创建更易读的代码,并使现有和未来的应用程序变得非常容易开发人员理解代码。
提示:
不要在代码中直接使用互斥锁,而是编写一个可重用的包装类,这样可以使代码更易于维护,以防您想要更改实现或添加调整。 请记住使用一次性模式删除互斥体,否则您会遇到问题!
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:
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!
对 CreateMutex 示例的 Google 搜索显示“MyMutex”是最常见的互斥体名称。
因此,您应该将互斥体命名为“NotMyMutex”以保证唯一性。
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.
您可以将您要防范的内容的描述与“Guard”一词结合起来
You could combine a description of what you're protecting against with the word "Guard"
我过去没有使用过 GUID,但我开始认为这是一个好主意 - 如果您考虑一下世界上所有使用不同软件的开发人员。
除非您正在想出一些非常晦涩的名称,并且可以确保它们是唯一的,否则您应该考虑 GUID。
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.