I have inherited some code that has a set of real-time values that are captured over a serial link that runs on a separate thread:
class Data
{
public static int nFooCount;
public static decimal meanValue;
// Lots more of a variety of types.
}
The thread just stores the data into the field with no locking or other synchronization. Looks like a whole sea of race conditions to me. So I want to add some safety to it. The question is, what’s best?
I could make the int fields volatile. Can’t do that with the decimal types, though. Interlocked can help with that, albeit messily, using boxing. Or I could add a lock object
private static readonly object lockObj = new object();
and then accessor everything. But this locks all the fields even when it will only modify one at a time. I can’t lock on primitives and that would be bad form anyway, and adding a lock object for every field would look wasteful. So is there a better way?
You could lock according to required access level using
ReaderWriterLockSlim. You could do this better by turning them into a property:This allows for multiple reads and single writes.