Changing Thread-Safety Dynamically
Sometimes there may be a need to decide dynamically (through code in your program) whether a class is thread-safe or not. This is the technique I use:
public class SomeClass
{
private Boolean threadSafe = false;
private readonly Object syncRoot = new Object();
//gets or sets whether this object is thread-safe or not
//in this case we are locking directly on the syncRoot field
public Boolean ThreadSafe
{
get { lock(this.syncRoot) { return(this.threadSafe); } }
set { lock(this.syncRoot) { this.threadSafe = value; } }
}
//Property used for thread synchronization
public Object SyncRoot
{
get
{
return(this.ThreadSafe == true ? this.syncRoot : new Object());
}
}
public void SomeMethod()
{
//always lock on the SyncRoot property, not the syncRoot field
lock (this.SyncRoot)
{
//do something
}
}
}