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.