gpt4 book ai didi

c# - 原子列表-此集合线程安全且快速吗?

转载 作者:行者123 更新时间:2023-12-03 13:21:17 26 4
gpt4 key购买 nike

我试图找出拥有一个集合的最佳方法,该集合将能够同时迭代,添加项目和从不同线程中删除所有项目。性能对于迭代组件至关重要,但是不会经常添加和删除项-因此添加/删除性能的重要性稍差一些。

这是我想出的:

public class AtomicList<T> : IEnumerable<T>
{
private readonly object Locker = new object();
private List<T> InternalCollection = new List<T>();

public void Add(T Value)
{
lock (Locker)
{
List<T> Update = new List<T>(InternalCollection);
Update.Add(Value);
InternalCollection = Update;
}
}

public void Remove(T Value)
{
lock (Locker)
{
List<T> Update = new List<T>(InternalCollection);
Update.Remove(Value);
InternalCollection = Update;
}
}

public IEnumerator<T> GetEnumerator()
{
return InternalCollection.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

这样做有什么弊端吗?像我上面描述的那样,如果不是线程安全/可迭代的,是否会发生任何情况?

另外-使用foreach和IEnumerable是否会降低性能成本?如果直接访问InternalCollection并对其进行for语句,会更好吗?

最佳答案

如果您不同时调用Add和Remove方法,则不需要lock,因为您只从InternalCollection字段引用的列表中进行读取。使用Interlocked.Exchange Method以线程安全的方式用新列表替换旧列表:

public class AtomicList<T> : IEnumerable<T>
{
private List<T> internalCollection = new List<T>();

public void Add(T vlue)
{
List<T> update = new List<T>(internalCollection);
update.Add(value);
Interlocked.Exchange(ref internalCollection, update);
}

public bool Remove(T value)
{
List<T> update = new List<T>(internalCollection);
bool removed = update.Remove(value);
if (removed) Interlocked.Exchange(ref internalCollection, update);
return removed;
}

public IEnumerator<T> GetEnumerator()
{
...

关于c# - 原子列表-此集合线程安全且快速吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11085444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com