Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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

        }

    }

}

Posted: Mar 21 2009, 10:34 AM by Ricardo Peres | with 4 comment(s)
Filed under:

Comments

Anon said:

Have you thought about using the monitor class instead?

# March 22, 2009 2:02 AM

Ricardo Peres said:

Anon,

This way, I can use a Monitor (or a lock block, which is the same), and don't care if the object is actually thread-safe or not:

SomeClass c = ...;

lock (c.SyncRoot)

{

 //may or may not be thread-safe

 c.SomeMethod();

}

# March 22, 2009 5:54 AM

Hotel Albena said:

Nobody can be exactly like me. Again yet I make trouble doing it.

# May 5, 2010 12:31 AM

serivce said:

I really liked your article.Much thanks again. Keep writing.

# May 8, 2012 2:21 AM