Лучшие практики для блокировки (или входа / выхода) в C #

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

5
задан ken 4 May 2011 в 04:24
поделиться