我创建了一个单独的依赖项来执行锁定和解锁,并且选择实现是 .NET 中的 Mutex 类。
interface ISynchronize
{
void Lock(lockId);
void Release(lockId);
}
应用程序使用此依赖项来获取和释放锁,如下所示
Trace.WriteLine($"LOCK ({System.Threading.Thread.CurrentThread.ManagedThreadId}) Before locking Star ID {starId}");
this.Synchronizer.Lock(starId);
Trace.WriteLine($"LOCK ({System.Threading.Thread.CurrentThread.ManagedThreadId}) After locking Star ID {starId}");
SomeWorkToBeDone();
Trace.WriteLine($"LOCK ({System.Threading.Thread.CurrentThread.ManagedThreadId}) Before Releasing Star ID {starId}");
this.Synchronizer.Release(starId);
Trace.WriteLine($"LOCK ({System.Threading.Thread.CurrentThread.ManagedThreadId}) After Releasing Star ID {starId}");
系统间歇性地生成异常,并带有以下跟踪
LOCK (53) Before locking Star ID 1
LOCK (53) After locking Star ID 1
LOCK (53) Before Releasing Star ID 1
Exception thrown: 'System.ApplicationException' in mscorlib.dll
Object synchronization method was called from an unsynchronized block of code.
请注意线程 ID 是相同的,因此没有人可以说试图释放它的线程可能不拥有它。还有什么可能发生的?我不应该创建新对象并使用TryOpenExisting
吗?
下面是依赖的实现
public void Lock(string lockId)
{
var mutex = new Mutex(false, lockId);
if (mutex.WaitOne(TimeSpan.FromSeconds(secondsToWait)) == false)
{
throw new SynchronizationTimedOutException($"Could not acquire lock within configured {secondsToWait} second(s)");
}
}
public void Release(string lockId)
{
var mutex = new Mutex(false, lockId);
mutex.ReleaseMutex();
}