如何避免同步锁异常?
我在 Monitor.Exit(resource); 中遇到此错误 如果我使用 Monitor.TryEnter(resource) 然后在几种方法后退出它,总是会出现此错误。我想将它与“ref bool”一起使用作为锁,但它不起作用。
Monitor.TryEnter(fork[second]);
if (Monitor.TryEnter(fork[second])&&fork[second].IsUsing == false)
{
fork[second].IsUsing = true;
del.Invoke(String.Format("Ph {0} took {1} ", philosopherName, second + 1));
PauseCheck(rd.Next(60, 100));
Monitor.TryEnter(fork[number]);
if (Monitor.TryEnter(fork[number])&&fork[number].IsUsing == false)
{
entermon1 = true;
Monitor.Exit(fork[second]);
fork[number].IsUsing = true;
Monitor.Exit(fork[number]);
checkph = true; DonotNeed = true;
}
if (entermon1 == false)
{
Monitor.Exit(fork[second]);
}
entermon1 = false;
}
I`ve got this error in Monitor.Exit(resource);
This error always appears if i use Monitor.TryEnter(resource) and then exit it after several methods.I wanted to use it with "ref bool" as a lock but it doesn't work.
Monitor.TryEnter(fork[second]);
if (Monitor.TryEnter(fork[second])&&fork[second].IsUsing == false)
{
fork[second].IsUsing = true;
del.Invoke(String.Format("Ph {0} took {1} ", philosopherName, second + 1));
PauseCheck(rd.Next(60, 100));
Monitor.TryEnter(fork[number]);
if (Monitor.TryEnter(fork[number])&&fork[number].IsUsing == false)
{
entermon1 = true;
Monitor.Exit(fork[second]);
fork[number].IsUsing = true;
Monitor.Exit(fork[number]);
checkph = true; DonotNeed = true;
}
if (entermon1 == false)
{
Monitor.Exit(fork[second]);
}
entermon1 = false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法锁定值类型 - 只能锁定对象,并且您绝对不想锁定装箱值,除非您维护对该框的引用。
我的猜测是,您在
Monitor.TryEnter
由于另一个线程拥有该锁而返回 false 之后调用了Monitor.Exit
- 如果您已经拥有该锁,则应该仅退出该锁。You can't lock on value types - only on objects, and you definitely don't want to lock on a boxed value unless you're maintaining a reference to that box.
My guess is that you're calling
Monitor.Exit
afterMonitor.TryEnter
returned false due to another thread owning the lock - you should only exit the lock if you already own it.