c# - Mutex.ReleaseMutex() 即使同一个线程拥有它也会产生同步错误
问题描述
我创建了一个单独的依赖项来执行锁定和解锁,并且选择实现是 .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();
}
解决方案
推荐阅读
- julia - <: 在朱莉娅中是什么意思?
- javascript - 访问 BootstrapVue 内部数据
- mailchimp - 每次有人通过我的 MailChimp 表单注册时,我如何才能收到通知?
- r-markdown - 在 RMarkdown 中将 kable 编织到 PDF,其中包含表值中的特殊字符
- extjs - 问题 Fieldset 标签在 chrome 87.0.4280.67 上使用 Sencha ExtJs 7.x 不可见
- json - Log4j 打印转义的 JSON 字符串而不是 JSON 对象
- python - 多处理建议和停止进程
- c++ - 如果函数模板已经推断出返回类型,有没有办法在不实例化定义的情况下调用它?
- imagemagick - 将具有 54x54 正方形 (540x540) 的图像大小调整为 54x54 像素无损
- servicenow - UiPath - 无法插入 ServiceNow 表记录:System.AggregateException