I’ve got a class with several properties. On every value update, a Store method is called which stores all fields (in a file).
private int _Prop1;
public int Prop1 {
get {
return _Prop1;
}
set {
_Prop1 = value;
Store();
}
}
// more similar properties here...
private XmlSerializer _Ser = new ...;
private void Store()
{
lock (_Ser) {
using (FileStream fs = new ...) {
_Ser.Serialize (fs, this);
}
}
}
Is this design thread-safe?
(Btw, if you can think of a more appropriate caption, feel free to edit.)
I think it is thread safe. If properties are changed on multiple threads, the values will be set in random order, atomic Stores will happen in a random order, but in the end, every property will have its latest value, and at the very end, an atomic Store happens, ensuring that the file is up-to-date.
Clarification: The properties will not be set very often, but they may be set at the same time. What matters is having a valid file most of the time.
If a thread is going to change a property with regards to a property value, it has to lock on the whole object to sync with other threads. That’s basically the same as with locking on a List on enumeration and is not a responsibility of this class.
There’s not enough code to make the call. But sure, nothing good is going to happen if you don’t serialize write access to the file. The 2nd thread that assigns the property is going to bomb on an IOException if the 1st thread is still busy writing the file.
Fine-grained locking like this is usually a problem. The client code could be busy changing more than one property of the class. You’ll get a partial update if an exception is raised, producing a file that contains serialized state that is invalid and may cause trouble when it is read. You’ll need something like a BeginUpdate(), EndUpdate() pair.