使用互斥锁的正确方法:
private static Mutex mutex;
static void Main()
{
bool created;
mutex = new Mutex(false, "YourAppName-{add-your-random-chars}", out created);
if (!created)
{
MessageBox.Show("Another instance of this application is already running");
return;
}
Application.Run(new Form1());
}
以上方法无法检测同一台机器上不同用户账户下运行该应用程序的情况。类似的情况还有进程可以同时在服务主机和独立模式下运行。为了解决这些问题,请按照以下方式创建互斥对象:
var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
var mutexsecurity = new MutexSecurity();
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));
_mutex = new Mutex(false, "Global\\YourAppName-{add-your-random-chars}", out created, mutexsecurity);
这里有两个不同之处 - 首先,互斥对象需要使用安全权限创建,以允许其他用户帐户打开/获取它。其次,在服务主机下运行的服务情况下,名称必须以"Global"为前缀(不确定其他用户在同一台计算机上运行的情况)。