小编Cil*_*lan的帖子

锁定语句似乎不起作用

我有这个方法:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我从多个线程调用它(调用相同的实例),但在TableProperty.Single上抛出异常(Sequence不包含任何元素).在调试代码时,我看到在另一个线程检查了缓存是否存在之后,正在创建一个从数据库中删除项目的情况.除非lock语句中有多个线程(syncroot对象绝对是跨线程的相同实例),否则这是不可能的.

不可能?我有证据: 不可能的情况

lock语句中有三个线程!是什么赋予了?

笔记: …

c# multithreading locking

5
推荐指数
1
解决办法
2574
查看次数

标签 统计

c# ×1

locking ×1

multithreading ×1