Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe queue (list) in .net

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

like image 591
Ben Foster Avatar asked Oct 20 '10 14:10

Ben Foster


People also ask

Is .NET queue thread-safe?

Queue class also provides FIFO data structure but it is not safe to use with multi-threading environment. To provide thread-safety, we have to implement locking around Queue methods which is always error prone.

What is thread-safe list in C#?

Thread Safe List With the ConcurrentBag Class in C# The ConcurrentBag class is used to create a thread-safe, unordered collection of data in C#. The ConcurrentBag class is very similar to the List in C# and can be used as a thread-safe list in C#. To use the ConcurrentBag class, we have to import the System.

Is ArrayList thread-safe C#?

To guarantee the thread safety of the ArrayList, all operations must be done through this wrapper. Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception.

Is list thread-safe?

A thread-safe variant of ArrayList in which all mutative operations (e.g., add, set, remove..) are implemented by creating a separate copy of an underlying array. It achieves thread safety by creating a separate copy of the List which is different than vector or other collections used to provide thread-safety.


1 Answers

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.

like image 82
Philip Rieck Avatar answered Sep 22 '22 10:09

Philip Rieck