在什么情况下SynchronizedCollection <t> .Remove()会返回false?

时间:2016-12-19 23:27:33

标签: c# multithreading

SynchronizedCollection<T>.Remove()https://msdn.microsoft.com/en-us/library/ms619895(v=vs.110).aspx)的MSDN文档声明此函数返回

  

如果项目已从集合中成功删除,则为true;否则,错误。

除了项目不在列表中之外,在其他情况下,这将返回false?

例如,如果集合被锁定,它会返回false还是等到它被解锁才能删除该项?

1 个答案:

答案 0 :(得分:5)

如果它可以获得锁定,然后如果该项目存在于集合中,它将返回true。否则它将返回false。

你可以调用Remove(),但是其他一些线程正在处理集合,你无法获得锁定。其他线程可能会在您获得锁定之前删除该项目。锁定后,该项目已被删除,因此它将返回false

在下面的代码中,很明显当你调用Remove时它会尝试获取一个锁,如果不成功,它会等到它可用。一旦可用,它将检查该项目是否仍在那里。如果不是,则返回false。如果是,则会调用RemoveAt

以下是从SynchronizedCollection<T>类的源代码支持上述内容的代码:

public bool Remove(T item) {
   lock( this.sync ) {
      int index = this.InternalIndexOf( item );
      if( index < 0 )
         return false;

      this.RemoveItem( index );
      return true;
   }
}

protected virtual void RemoveItem(int index) {
   this.items.RemoveAt( index );
}
相关问题