I am new to multi-threading in C#. But from reading various chapters in C# books and tutorials. I know that the best way to develop classes which are used in multithreaded applications is to create immutable classes.
But I am not too sure about how to deal with classes that expose a read/write property. In some articles that I have read the author has placed locks around the read/write property e.g.
public class Test
{
private string property1;
public string ClassProperty
{
get
{
lock
{
return Property1;
}
}
set
{
lock
{
Property1 = value;
}
}
}
}
I know that with any shared variable declared and used within a class that it needs to be locked in multithreaded applications. But some articles that I have read have suggested that the above code will not work if the property being exposed is a reference type. Others have suggested that you cannot make a class with exposed properties thread-safe? Does anyone have a definite answer on this topic?
Thanks
That code sample doesn’t do anything except add overhead. C# String objects by themselves are thread-safe anyway and pointer read/writes are always atomic. That code sample would only make sense for a double or a struct.
You should not think about making individual properties thread-safe as much as making larger logical operations “atomic”. For example if you have two field foo and bar and it must always be the case that bar == lowercase(foo) then you should protect operations which access any of them with the same lock.
A better example would be an object which must be contained in both a vector and a hash: