Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

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 7 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

gurfaleunfore said:

What method is euphemistic pre-owned to state a open bumper that has been MINIMALLY bent inwards? I be acquainted with down heat treatment. Is that completely successful? I wouldn't call it a dent, more like a rickety take care of in the upstanding specialty, about 4 inches long, that occurs from hitting a metal hop-pole laterally, so that the staff forces the bumper inwards slightly?

<a href=www.dial1auto.com/bumper-repair.php>tustin bumper repair</a>

# September 27, 2009 7:25 PM

Hotel Albena said:

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

# May 5, 2010 12:31 AM

sdfsdgfd said:

I’ve been visiting your blog for a while now and I always find a gem in your new posts.  Thanks for sharing.

# April 14, 2011 9:06 PM

serivce said:

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

# May 8, 2012 2:21 AM

bookmarking said:

jW1BiT This is one awesome article.

# May 11, 2012 12:59 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)