Przemysław Michalski
Przemysław Michalski

Reputation: 9847

C# using lock practice

I have critical section in my application which contains a lot of code: which is better way to locking access in threadMethod:

A) lock all block:

private object locker = new object();

private void threadMethod()
{
   while(true)
   {
      lock(locker)
      {
         // do work - a lot of code here
      }
      Thread.Sleep(2000);
   }
}

B) Use additional locked access member canWork:

 private static object locker = new object();
 private bool canWork;
 private bool CanWork
 { 
     get { lock(locker) { return this.canWork; } }
     set { lock(locker) { this.canWork = value; } } 
 }

  private void threadMethod()
  {
     while(true)
     {
        if(CanWork)
        {
           // do work - a lot of code here
        }
        Thread.Sleep(2000);
     }
  }

and somewhere in code

CanWork = false;

Upvotes: 3

Views: 1777

Answers (4)

Eric Ouellet
Eric Ouellet

Reputation: 11754

est link:

http://msdn.microsoft.com/en-us/magazine/cc188793.aspx#fig7

Best usage is - declare a new private sync object - use "lock(synObject) { code here ... }

Upvotes: 0

Phil Baines
Phil Baines

Reputation: 205

I would use the Monitor instead. Plus do you really want while(true) because this will repeat forever?

  private object syncObject = new object();

  private void threadMethod()
  {
   bool tryToRun = true;
   while(tryToRun)
   {
    if(Monitor.TryEnter(syncObject))
    {
     tryToRun = false;

     // do work - a lot of code here

     Monitor.Exit(syncObject);
    }
    else
    {
     Thread.Sleep(2000); // Possibly knock this up the how long you expect the lock to be held for.
    }
   }
  }

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838216

Neither is particularly good.

  • The first has the disadvantage that you hold the lock for a long time.
  • The second has the disadvantage that the state can change after you check it.

Instead try to pass immutable arguments to your method (for example a copy of the data). You will probably still need to lock for constructing the arguments and for collecting the results but this is hopefully a much shorter period of time.

Upvotes: 4

alpha-mouse
alpha-mouse

Reputation: 5003

The second approach will likely lead to race conditions. Can your "a lot of code" be separated in several critical/non critical chunks?

Upvotes: 1

Related Questions