suppose a server storing an ImmutableHashSet of connection data
ImmutableHashSet<ConnectionData> connections = new ...
I then have various calls adding/removing/reading from this, ie:
OnConnected(connectionData) => connections = connections.Add(connectionData);
OnDisconnected(connectionData) => connections = connections.Remove(connectionData);
My question is, in the above calls which only do a single operation on the HashSet (Add/Remove), should I lock connections ? or are ImmutableHashSet operations thread safe?
Your pattern of assigning the value directly back onto the collection is not thread-safe. However, you generally do not want to lock when using an immutable collection. One of the major features of these collections are lock-free manipulation, which is often significantly more performant. Instead, use the ImmutableInterlocked class:
ImmutableHashSet<ConnectionData> connections;
ImmutableInterlocked.Update(ref connections,
(collection, item) => collection.Add(item),
connectionData);
ImmutableInterlocked.Update(ref connections,
(collection, item) => collection.Remove(item),
connectionData);
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