我们有一个可以运行多个实例的旧版 VB6 可执行文件。我们希望某些工作只允许一个并发实例。
似乎 OS Mutex 非常适合,因为这是一个遗留应用程序,所有新代码都必须用 C# 编写并通过互操作访问。
我创建了一个将获得的类:
public bool AcquireLock(string JobId)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
appGuid = appGuid + JobId;
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
bool mutexExists = false;
var mutex = new Mutex(true, mutexId, out mutexExists);
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
mutex.SetAccessControl(securitySettings);
return mutexExists;
}
并释放锁:
public bool ReleaseLock(string JobId)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
appGuid = appGuid + JobId;
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
var mutex = Mutex.OpenExisting(mutexId);
mutex.ReleaseMutex();
return true;
}
在我尝试释放锁之前,一切似乎都运行良好:
[TestMethod()]
public void ReleaseLockTest()
{
var target = new MutexConcurrencyHelper();
var jobId = RandomUtils.RandomString(8, true);
var expected = true;
bool actual;
actual = target.AcquireLock(jobId);
Assert.AreEqual(expected, actual);
target.ReleaseLock(jobId);
var expected1 = true;
bool actual1;
actual1 = target.AcquireLock(jobId);
Assert.AreEqual(expected1, actual1);
}
获得锁的第二次尝试发现锁已经到位。为什么这个锁不释放?