如何避免同步锁异常?

发布于 2024-11-03 21:10:49 字数 797 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罪#恶を代价 2024-11-10 21:10:49

您无法锁定值类型 - 只能锁定对象,并且您绝对不想锁定装箱值,除非您维护对该框的引用。

我的猜测是,您在 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 after Monitor.TryEnter returned false due to another thread owning the lock - you should only exit the lock if you already own it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文