There are some cases where I really like using Guava's Striped class.
Is there an equivalent in C#?
It doesn't look like there is a direct equivalent, but there are some lockless thread-safe collection options (I'm not sure what you're trying to achieve, so I can't say if they will work for your scenario). Have a look at the System.Collections.Concurrent Namespace.
In particular, ConcurrentBag, ConcurrentQueue, ConcurrentStack, and ConcurrentDictionary all have different locking/lockless thread-safe strategies. Some are explained in this blog post.
You might be able to get what you want via the Partitioner class, although I am unsure of the implementation.
@Behrooz is incorrect in saying that all .net framework types only use a single lock for the entire list. Take a look at the source for ConcurrentDictionary. Line 71 suggests that this class is implemented using multiple locks.
If you really want to, you could write your own version. The source for the Guava Striped is: https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/Striped.java
I think best you can do is implementing your own because all dotnet framework types offer only one lock
for the entire list.
To do that you can use the GetHashCode()
function, modulus(%
) it with the number of stripes you want. and use it as an index for Tuple<TLock, List<T>>[]
where TLock can be any kind of lock defined in System.Threading
namespace and T is the type you want to store/access.
With this you can decide how you want your stripes to be stored. There are choices like HashSet
(inefficient in your case since you already use some of the bits to calculate the stripe index), SortedSet
, List
, Array
.
btw, Thank you for the question, It's gonna help me solve a problem I'm having.
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