[英]Under what circumstances would SynchronizedCollection<T>.Remove() return false?
SynchronizedCollection<T>.Remove()
( https://msdn.microsoft.com/en-us/library/ms619895 ( v= SynchronizedCollection<T>.Remove()
的MSDN文檔聲明此函數返回
如果項目已從集合中成功刪除,則為true; 否則,錯誤。
除了項目不在列表中之外,在其他情況下這將返回錯誤嗎?
例如,如果集合被鎖定,它會返回false
還是等到解鎖后才能刪除該項?
如果它可以獲取一個鎖,然后如果該項存在於集合中,它將返回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 );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.