[Edit: It seems that the original question was about a double, not an integer. So I think this question is worth it if we change the integer to double.]
I have a rare problem reading integer properties from a class used in multiple threads that sometimes returns a null value. After initialization, the values ββdo not change.
This question points to this. The consensus is that although I am accessing an integer, I need to synchronize the properties. (Some of the original answers have been deleted). I did not select the answer there because I have not solved the problem yet.
So, I did some research on this, and I'm not sure which of the .Net 4s locking mechanisms to use or if the locks should be outside the class itself.
Here is what I thought about using:
public class ConfigInfo { private readonly object TimerIntervalLocker = new object(); private int _TimerInterval; public int TimerInterval { get { lock (TimerIntervalLocker) { return _TimerInterval; } } } private int _Factor1; public int Factor1 { set { lock (TimerIntervalLocker) { _Factor1 = value; _TimerInterval = _Factor1 * _Factor2; } } get { lock (TimerIntervalLocker) { return _Factor1; } } } private int _Factor2; public int Factor2 { set { lock (TimerIntervalLocker) { _Factor2 = value; _TimerInterval = _Factor1 * _Factor2; } } get { lock (TimerIntervalLocker) { return _Factor2; } } } }
But I read that it is terribly slow.
Another alternative is to lock the ConfigData instance on the user side, but it seems to be a lot of work. Another alternative I've seen is Monitor.Enter and Monitor.Exit , but I think Lock is the same with less syntax.
So what is best for creating a class property stream safely?
Rich shealer
source share