[dba-VB] c# lock()

jwcolby jwcolby at colbyconsulting.com
Sat Mar 26 16:53:15 CDT 2011


Shamil,

I am trying to build a base class which contains a set of lock objects and some standard variables. 
  Having defined the lock objects static per your code below, the derived class cannot access the 
lock objects even though I set them protected:

protected static Object LockBln = new Object();

In the derived class when I try to access it:

lock(this.LockBln)
{
}

I get a compile error:

"Member cannot be accesses with an instance reference; Qualify it with a type name instead."

What does this mean?

Reading on the internet it says that static properties are shared between all instances of the 
class.  I don't see how I can share a property between 50 instances and then use a 
lock(MyStaticProperty) {}.

I'm so confused...

John W. Colby
www.ColbyConsulting.com

On 3/25/2011 5:05 PM, Shamil Salakhetdinov wrote:
> Hi John --
>
> Your sample is a correct usage of locking - just use static thisLock
> variable
>
> private static Object thisLock = new Object()
>
> as non-static variable *is not* thread safe AFAIU.
>
> Yes, such locking can be done for various operations of that class - just
> make sure you'll not get dead-locked...
> Also use *one lock object* to lock *one resource* in a class - otherwise
> "deadlock" will become your "everyday guest"...
>
> Thank you.
>
> --
> Shamil
>
> -----Original Message-----
> From: dba-vb-bounces at databaseadvisors.com
> [mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of jwcolby
> Sent: 25 ????? 2011 ?. 22:58
> To: Discussion concerning Visual Basic and related programming issues.
> Subject: Re: [dba-VB] c# lock()
>
> Shamil,
>
> Does this allow using a single "lock object" to lock various operations in a
> class.
>
> For example I want to lock a date flag variable while using a property to
> either get or set the variable.
>
>           private Object thisLock = new Object();
>
>           public DateTime pFlagDte {
>               get {
>                   lock (thisLock)
>                   {
>                       return dteFlag;
>                   }
>               }
>               set
>               {
>                   lock (thisLock)
>                   {
>                       dteFlag = value;
>                   }
>               }
>           }
>
> The issue is not multiple threads trying to write to the date variable but
> rather one thread trying to read it while another is writing it.
>
> John W. Colby
> www.ColbyConsulting.com



More information about the dba-VB mailing list