I have a class that is designed primarily as a POCO class, with various Threads and Tasks could read its values, and only others only occasionally updating these values. This se
You have a few options.
lock
.volatile
.Interlocked
set of methods.Since reads and writes to a bool
are guaranteed to be atomic then you may not need to do anything. This will very much depend on the nature of the way your class is going to be used. Atomicity does not equal thread-safety. It is only one aspect of it.
The ideal solution is to make your class immutable. Immutable classes are generally thread-safe because they cannot be modified by other threads (or at all for that matter). Sometimes this just is not feasible though.
My next preference on the list is a plain old lock
. The overhead of acquiring and releasing is very minimal. In fact, I think you will find that a lock
will beat out a ReaderWriterLockSlim
in most situations especially if all you are doing is reading/writing a variable. My own personal tests indicate that the overhead of RWLS is about 5x slower than a lock
. So unless the read operations are unusually long and that they significantly outnumber write operations then RWLS will not help.
If you are concerned about lock overhead then by all means mark the fields as volatile
. Just remember that volatile
is not a magic bullet that solves all concurrency issues. It is not intended as a replacement for lock
.