When reading the MSDN documentation it always lets you know if a class is thread safe or not. My question is how do you design a class to be thread safe? I am not talking about
non generic ICollection classes provide properties for thread safety. IsSynchronized and SyncRoot. unfortunately you cannot set IsSynchronized. You can read more about them here
In your classes you can have something simlar to IsSynchronized and Syncroot , expose public methods/properties alone and inside method body check for them. Your IsSynchronized will be a readonly property, so once your instance is initialized, you will not be able to modify it
bool synchronized = true;
var collection = new MyCustomCollection(synchronized);
var results = collection.DoSomething();
public class MyCustomCollection
{
public readonly bool IsSynchronized;
public MyCustomCollection(bool synchronized)
{
IsSynchronized = synchronized
}
public ICollection DoSomething()
{
//am wondering if there is a better way to do it without using if/else
if(IsSynchronized)
{
lock(SyncRoot)
{
MyPrivateMethodToDoSomething();
}
}
else
{
MyPrivateMethodToDoSomething();
}
}
}
You can read more about writing thread safe collections on Jared Parson's blog