This is a detailed question for C #.
Suppose I have a class with an object, and this object is protected by a lock:
Object mLock = new Object(); MyObject property; public MyObject MyProperty { get { return property; } set { property = value; } }
I want the poll thread to be able to request this property. I also want the thread to periodically update the properties of this object, and sometimes the user can update this property, and the user wants to see this property.
Will the following code correctly block data?
Object mLock = new Object(); MyObject property; public MyObject MyProperty { get { lock (mLock){ return property; } } set { lock (mLock){ property = value; } } }
"Right," I mean, if I want to call
MyProperty.Field1 = 2;
or something else, will the field be locked during the update? Is the setup performed by the equals statement inside the scope of the get function, or does the get function (and therefore the lock) end first, and then the setup is called, and then set, bypassing the lock?
Edit: since this apparently won't do the trick, what will happen? I need to do something like:
Object mLock = new Object(); MyObject property; public MyObject MyProperty { get { MyObject tmp = null; lock (mLock){ tmp = property.Clone(); } return tmp; } set { lock (mLock){ property = value; } } }
which more or less simply ensures that I only have access to the copy, which means that if I had two streams calling "get" at the same time, each of them would start with the same Field1 value (on the right ?). Is there a way to make reading and writing a lock on a property that makes sense? Or should I just limit myself to locking on function sections, not the data itself?
Just to make this example make sense: MyObject is a device driver that returns status asynchronously. I send commands through the serial port, and then the device responds to these commands in due time. Right now I have a thread that polls it for its status ("Are you still there? Can you accept commands?"), A thread waiting for replies to the serial port ("Just received status bar 2, all is good")) and then a UI thread that accepts other commands ("The user wants you to do this.") and sends the responses from the driver ("I just did, now update the interface with this"). Therefore, I want to block the object itself, not the fields of the object; this would be a huge number of locks, a and b, not all devices of this class have the same behavior, just common behavior, so I would have to code many separate dialogs if I individualized the locks.