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?
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With