Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Immutable HashSet locking

Tags:

c#

c#-7.0

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?

like image 511
kofifus Avatar asked Dec 17 '25 12:12

kofifus


1 Answers

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);
like image 107
Cory Nelson Avatar answered Dec 19 '25 05:12

Cory Nelson



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!