![](/img/trans.png)
[英]Is modifying SynchronizedCollection combined by Linq, await and Parallel.ForEach thread safe?
[英]How to make ENumerable operations tread safe SynchronizedCollection?
當我使用SynchronizedCollection
,我可以捕獲異常
System.InvalidOperationException
Collection was modified; enumeration operation may not execute.
在foreach
周期中。
如果查看SynchronizedCollection類的源代碼,即在GetEnumerator方法中(實際上有兩個,其中一個是顯式接口實現),您將看到:
List<T> items;
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList)this.items).GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
lock (this.sync)
{
return this.items.GetEnumerator();
}
}
編輯。 我問的不是在並發情況下該怎么辦。 我問
如何使其線程安全?
我認為有兩種解決方案:
第二個方面的性能成本要安全得多。
如果您使用的是.NetCore,則ImmutableList <T>是快照的更好方法,並且可以避免淺拷貝問題。
我使用了SynchronizedCollection類,並使用了foreach (var element in this.items) yield return element;
這里公共新的IEnumerator GetEnumerator()
從基類使用構造函數,這足以使其成為線程安全的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.