A variable equivalent of a blocking collection in C#

336 views Asked by At

This may have an obvious answer but I will ask anyway.

Is there a variable equivalent of the blocking collection for C#? What I want is for all my threads to be able to access a shared variable. It will not be a collection, just a shared variable that will be adjusted in value as each thread uses it. What I like about the blockingcollection is that ques, and locks, are managed by C#, and was hoping there was something similar for just a variable?

I could use a public static variable and create the lock myself but thought I should check.

EDIT: Would the interlock be a possibility.

1

There are 1 answers

0
Yosef O On

What sort of variable and what do you want to do with this variable?

Interlocked will allow you access a variable in an atomic way.

This means that for primitive type (int, float, object ref) you can perform a few primitive actions (increment, swap values, etc) in an atomic and therefore thread safe way. For example, if you want a counter to be incremented/decremented from multiple threads this could be a good solution.

Other (more powerful) uses include conditional atomic swaps, which are part of a idiom of software transactional memory and allow safe changes to a variable from multiple threads without using other synchronization mechanisms (such as a mutex).

However, interlocked operations must perform some locking on the hardware level and so have a certain performance penalty and are not a magic wand for multi threaded data access and race conditions.

Also, they only really work on primitive types and operations. Interleaving a few operations on a few types at the same time requires more wiring and is not directly supported by interlocked class.