Thread safe queue (list) in .net

Ben Foster picture Ben Foster · Oct 20, 2010 · Viewed 14.6k times · Source

I need to create a thread safe list of items to be added to a lucene index.

Is the following thread safe?

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);
        }
    }
}

Is it necessary to lock even when getting items from the internal list?

The idea is that we will then have a separate task running to grab the items from indexqueue and add them to the lucene index.

Thanks Ben

Answer

Philip Rieck picture Philip Rieck · Oct 20, 2010

Your implementation seems thread-safe, although you will need to lock when reading from items as well - you can not safely read if there is a concurrent Add operation. If you ever enumerate, you will need locking around that as well and that will need to live as long as the enumerator.

If you can use .net 4, I'd strongly suggest looking at the System.Collections.Concurrent namespace. It has some well tested and pretty performant collections that are thread-safe and in fact optimized around multiple-thread access.