C#中锁定(或进入/退出)的最佳实践

ken*_*ken 5 c# multithreading locking

我有一个测量仪器对象:

public class Instrument
{
  public double Measure() 
  { 
    return 0; 
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个需要做一些测量的设备:

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

测量仪器一次只能在一个设备上运行,但许多设备可能使用同一台仪器.我是线程新手,根据我的理解,以下两种解决方案都有警告.

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我已经读过最好锁定私有对象,但我不知道如何做到这一点,同时仍允许在Device上获取/设置MeasuringInstrument.有什么建议?

非常感谢,

Far*_*ker 5

如果instrument多次使用你devices的最佳做法是lock在你的instrument班级设置.所以第一个解决方案效果更好.

但最好是创建一个新的锁对象并在instrument课堂上使用它.

public class Instrument
{
  Object lockKey = new Object();
  public double Measure() 
  { 
    lock(lockKey)
    {
      return 0; 
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Jus*_*tin 3

通常的模式是创建自己的私有,object只是为了在明显的选择可能暴露在类之外的情况下进行锁定,例如:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,我怀疑您只需要这两个锁之一(要么是 inDoMeasuring要么是 in Measure),尽管这确实取决于丢失的位。