我需要创建一个线程安全的列表,用来添加到Lucene索引中。
以下是线程安全的吗?
public sealed class IndexQueue
{
static readonly IndexQueue instance = new IndexQueue();
private List<string> items = new List<string>();
private IndexQueue() { }
public static IndexQueue Instance {
get { return instance; }
}
private object padlock = new object();
public void AddItem(string item) {
lock (padlock) {
items.Add(item);
}
}
}
即使是从内部列表中获取项目,锁定是否仍然是必需的?
想法是我们将有一个单独的任务运行来从indexqueue中获取项目并将它们添加到lucene索引中。
谢谢
Ben
System.Collections.Concurrent
对你来说可能并不是很有用。它没有List
的等效物,即使有,你仍然可能需要应用自己的锁定来使项目的枚举具有原子性。这实际上取决于你希望多个线程如何感知枚举。 - Brian Gideon