I have this method:
public bool Remove(EntityKeyType key)
{
lock (syncroot)
{
//wait if we need to
waitForContextMRE.Wait();
//if the item is not local, assume it is not remote.
if (!localCache.ContainsKey(key)) return false;
//build an expression tree
Expression<Func<EntityType, bool>> keyComparitorExpression = GenerateKeyComparitorExpression(key);
var itemToDelete = TableProperty.Single(keyComparitorExpression);
//delete from db
TableProperty.DeleteOnSubmit(itemToDelete);
DataContext.SubmitChanges();
//get the removed item for OnCollectionChanged
EntityType itemToRemove = localCache[key];
itemToRemove.PropertyChanged -= item_PropertyChanged;
//remove from the list
Debug.Assert(localCache.Remove(key));
//call the notification
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, itemToRemove));
return true;
}
}
I am calling it from multiple threads (calling the same instance), but an exception keeps being thrown on TableProperty.Single (Sequence contains no elements). Upon debugging the code I saw that a situation is being created where the item is being deleted from the database after a different thread has checked the cache for its existence. This should not be possible unless there are multiple threads inside the lock statement (The syncroot object is definitely the same instance across threads).
Impossible? I have proof:

There are three threads inside the lock statement! What gives?
notes:
- The MRE is set (not blocking).
- This is not a situation where the exception gets thrown, it just shows multiple threads inside a lock section. Update: I changed the image to an intellitrace event of the exception. The old image is here
- The syncroot object is not static, because I only want calls to the same instance syncronized.
Update
This is the declaration of the syncroot object:
private object syncroot = new object();
And some other declarations:
private ManualResetEventSlim waitForContextMRE = new ManualResetEventSlim(true);
private DataContextType _dataContext;
private System.Data.Linq.Table<EntityType> _tableProperty;
//DataContextType and EntityType are generic type parameters
I cannot make the syncroot static because I have several instances of the class running and it is important that they don’t block each other. But that doesn’t really matter – making it static does not fix the problem.
The ManualResetEvent (waitForContextMRE) is not there for synchronization – it’s there to block database operations for a certain time after certain operations are performed (i.e. on startup). It is set most of the time. Taking it out of the lock block also does not fix the problem.
I have been debugging this problem for a while now and, although I have not resolved it, it is clear to me that the locks are working. I am guessing the problem is with the DataContext (which are known for being tricky in multithreaded situations).