我正在使用此代码阻止我的程序的第二个实例同时运行,是否安全?
Mutex appSingleton = new System.Threading.Mutex(false, "MyAppSingleInstnceMutx");
if (appSingleton.WaitOne(0, false)) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
appSingleton.Close();
} else {
MessageBox.Show("Sorry, only one instance of MyApp is allowed.");
}
Run Code Online (Sandbox Code Playgroud)
我担心如果有什么东西抛出一个异常并且应用程序崩溃了Mutex仍然会被保留.真的吗?
我尝试使用临时文件:
char *temp = tempnam(NULL, "myapp_");
printf("Tempname: %s", temp) // Prints /tmp/myapp_random
while (1) { }
Run Code Online (Sandbox Code Playgroud)
但当我检查/tmp(当应用程序仍在运行时),myapp_random不存在!
至于使用文件锁,我无法很好地掌握它,我试着看,<fcntl.h>但它似乎专注于文件的指定部分的锁.我只想将该文件完全用作锁(这就是为什么我更喜欢尝试临时文件的方法).
有任何想法吗?
我有两个应用程序,一个WinForms应用程序和一个Windows服务,它们都运行在同一台机器上.我希望WinForms应用程序能够可靠地检测服务何时运行.我完全控制了两个应用程序的设计和实现.
我的第一个想法是使用Mutex,由服务实例化并由WinForms App检测.
有更好的设计吗?