Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what circumstances would SynchronizedCollection<T>.Remove() return false?

The MSDN documentation for SynchronizedCollection<T>.Remove() (https://msdn.microsoft.com/en-us/library/ms619895(v=vs.110).aspx) states that this function returns

true if item was successfully removed from the collection; otherwise, false.

Other than if the item is not in the list, under what other circumstances would this return false?

For example, if the collection is locked, would it return false or would it wait until it is unlocked to remove the item?

like image 778
Matt Williams Avatar asked Dec 19 '16 23:12

Matt Williams


1 Answers

If it can acquire a lock and then if the item exists in the collection it will return true. Otherwise it will return false.

It is possible you call Remove() but some other thread is working on the collection and you cannot get a lock. That other thread may remove the item before you can get a lock. Once you have a lock, at that point the item has been removed so it will return false.

In the code below it is clear when you call Remove it tries to acquire a lock, if not successful it will wait till it is available. Once available, it will check if the item is still there. If not it returns false. If yes, it will call RemoveAt.

Here is the code to support what I am saying above from the SynchronizedCollection<T> class's source code:

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 );
}
like image 179
CodingYoshi Avatar answered Oct 03 '22 02:10

CodingYoshi