Here is the article I read http://kristofverbiest.blogspot.com/2008/11/creating-single-instance-application.html, followed the steps by the article, I have the following code, I'm almost sure it can't work and it can't:
static class Program
{
static Mutex mutex;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool alreadyRun;
mutex = new Mutex(false, Guid.NewGuid().ToString().Replace("-", ""), out alreadyRun);
if (!alreadyRun) return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
The article says the Mutex name passed in can be random, the MyAppName is just for easy debugging (so I left it out), 'Local//' was also left out. I wonder how it can work? That constructor will succeed and turn alreadyRun
true whenever the random GUID string is unique (I mean there hasn't been any Mutex with that name created before). That means, there is a very little chance for alreadyRun
becoming false. In fact, I've tried the code above for many times and I could run many instances of my application as I liked.
After trying a fixed string like "unique" for the mutex name , it simply works. However this won't work if there is some another application creating another mutex with the same name. And I now ended up with this solution:
- We can't use random string, we have to use fixed string and this string should be long and complicated, it is like your password, your id to be sure that there is little chance for any other application to use the same name. Here is an example that I'm sure to say, there is little chance for any other (even a machine) to think of:
ilove.netilovejava1234forever56789thismyid_itisevenlongerlongerlonger_howlongcanitbe_maybe8000characters?_canitbeso?
Please explain about the article (looks like it is from a pro blogger) and give me any other solution using Mutex (I've been fed up with using GetProcessesByName
, it's not good so far). Thanks!