开发者

Best practices for lock (or Enter/Exit) in C#

I ha开发者_如何学Pythonve a measuring instrument object:

public class Instrument
{
  public double Measure() 
  { 
    return 0; 
  }
}

I have a device that needs to do some measuring:

public class Device
{
  public Instrument MeasuringInstrument { get; set; }
  public void DoMeasuring()
  {
    var result = this.MeasuringInstrument.Measure();
  }
}

The measuring instrument can only operate on one device at a time, yet many devices may use the same instrument. I'm new to threading, and from what I understand, both of the following solutions have caveats.

public class Instrument
{
  public double Measure() 
  { 
    lock(this)
    {
      return 0; 
    }
  }
}

public class Device
{
  public Instrument MeasuringInstrument { get; set; }
  public void DoMeasuring()
  {
    lock(this.MeasurementInstrument)
    {
      var result = this.MeasuringInstrument.Measure();
    }
  }
}

I've read it's best to lock on private objects, but I don't know how to do that while still allowing the MeasuringInstrument to be get/set on the Device. Any suggestions?

Thanks much,

Ken


if your instrument is used by multiple devices the best practice is to set lock in your instrument class. so the fist solution works better.

but its better to create a new lock object and use it in instrument class.

public class Instrument
{
  Object lockKey = new Object();
  public double Measure() 
  { 
    lock(lockKey)
    {
      return 0; 
    }
  }
}


the usual pattern is to create your own private object just for locking in the case where the obvious choice might be exposed outside of the class, for example:

public class Instrument
{
    private object thisLock = new object();

    public double Measure() 
    { 
        lock(this.thisLock)
        {
            return 0; 
        }
    }
}

public class Device
{
    public Instrument MeasuringInstrument { get; set; }
    private object measuringInstrumentLock = new object();

    public void DoMeasuring()
    {
        lock(this.measuringInstrumentLock)
        {
            var result = this.MeasuringInstrument.Measure();
        }
    }
}

Also, I suspect that you only need one of those two locks (either the one in DoMeasuring or the one in Measure) although that does depend on the missing bits.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜