Mutexes with the same name

I'm relatively new to C# programming and some days ago, I came across the term mutex . It was used in the sense of avoiding running multiple instances of the same application. I was actually reading a book on WPF (using C#, of course) so there was no deep explanation on C# (the author wrote it for people with sufficient knowledge of C#).
It was used in this form:

Mutex mutex;
// ...

// Check for existing instance
string mutexName = "MyCompanyName.MyAppName";
bool createdNew;
mutex = new Mutex(true, mutexName, out createdNew);

// If there is an existing instance, shut down this one
if(!createdNew) { Shutdown(); }

My explanation of a mutex is that it is sort of a system-wide type. All single-instance applications access all mutexes in a system to prevent multiple instances. Also. a mutex should have a unique name . (Of course, I stand to be corrected; that's my own explanation so it could be wrong).

Suppose there happens to be a mutex named "mutexConflict" created by an application A while another application B (which was created by a completely different author) has its own mutex also named "mutexConflict" . If A is already running and B is about to be run, isn't there supposed to be a conflict? Will B run?


Yes, there is supposed to be a conflict. That's why choose such names for your mutexes (mutices? :))) that are likely to be unique.

If you want only one instance of your application to run at a time, all you need is open a named mutex in the beginning of your program, and, if it exists, shut down. That's the point of your exmaple and that's how it's implemented usually.


如果出于这个原因,该示例使用“MyCompanyName.MyAppName”,因为公司中的其他团队不太可能开发与您具有相同名称的应用程序


This is EXACTLY the point of a mutex. You have some key, and you want to provide mutually exclusive use of that key.

链接地址: http://www.djcxy.com/p/51218.html

上一篇: 被遗弃的互斥体异常

下一篇: 具有相同名称的互斥体