How to avoid a synchronizationlockexception?
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)
{
Monit开发者_Python百科or.Exit(fork[second]);
}
entermon1 = false;
}
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.
精彩评论