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];
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With