开发者

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;


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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜