Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a C# generic dictionary of structs thread safe if it doesn't resize?

If I preload a dictionary with structs and guarantee never to add any more items to it, will it be thread-safe if I update items from a single thread and read them from another.

struct DataItem
{
    public double Price;
    public double Size;
}

class Test
{
    Dictionary<string, DataItem> items = new Dictionary<string,DataItem>(3);
    public Test ()
    {
        items["A"] = new DataItem(){Price=100, Size=1000};
        items["B"] = new DataItem(){Price=200, Size=2000};
        items["C"] = new DataItem(){Price=300, Size=3000};
    }

One thread would call this method

    public void UpdateItem()
    {
        DataItem newItem = new DataItem(){Price=400, Size=4000};
        items["A"] = newItem;    
    }

A different thread would be calling this method

    public DataItem GetItem(string key)
    {
        return items[key];
    }
}
like image 754
user3053206 Avatar asked Nov 22 '25 12:11

user3053206


1 Answers

The documentation says:

A Dictionary<TKey, TValue> can support multiple readers concurrently, as long as the collection is not modified.

So it is not threadsafe to have both readers and writers operating simultaneously.

like image 191
David Heffernan Avatar answered Nov 25 '25 02:11

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!