Monday, March 21, 2011

System.Threading.SynchronizationLockException was caught

I was coding away some parallel threads today in C# when bam! This very vague exception kept getting thrown over and over again.

I had a block of code similar to this:
while (!Monitor.TryEnter(_removals)) ;
foreach (AlarmMessage alm in _removals)
{
RemoveAlarm(alm);
}
_removals = new List();
Monitor.Exit(_removals);

It looked all fine in my head. I lock the object (it was a List<>), I iterated through it and run a "remove" function on it, reset the list and then unlock the object.

However, on the Monitor.Exit I kept getting the System.Threading.SynchronizationLockException. Grrrrrrr.

I figured it out though. Obviously creating the new List<>() creates a brand new object. The lock was set with a reference on the original object, so when it comes to Monitor.Exit(), it's trying to unlock from the new reference. Woops. So instead of making a new List when I want to clear it, I just go the proper way and
_removals.Clear().

No comments:

Post a Comment