我们有一个串行端口,该串行端口连接到同一条线上的数百个物理设备。我们有Modbus和Hart之类的协议(protocol)来处理应用程序和设备之间的请求和响应。问题与管理 channel 的引用计数有关。当没有设备在使用该 channel 时,应关闭该 channel 。

public class SerialPortChannel
{
   int refCount = 0;
   public void AddReference()
   {
      refCount++;
   }


   public void ReleaseReference()
   {
      refCount--;
      if (refCount <= 0)
           this.ReleasePort(); //This close the serial port
   }

}

对于连接的每个设备,我们为该设备创建一个对象,例如
  device = new Device();
  device.Attach(channel);    //this calls channel.AddReference()

当设备断开连接时,
  device.Detach(channel); //this calls channel.ReleaseReference()

我不相信引用计数模型。在.NET World中是否有更好的方法来解决此问题?

最佳答案

您可以考虑使Attach返回实现IDisposable的类型。这将公开可用的端口成员,但是它们在内部将其委派回原始对象(除了Attach之外,不会公开公开其他任何对象);调用Attach将增加引用计数;处理返回的值会使它递减。然后,您可以执行以下操作:

using (Foo foo = device.Attach(channel))
{
    ...
}

要记住的一个奇怪之处是,您从引用计数0开始-但没有关闭端口。您是否应该只在第一个Attach调用中打开它?

关于c# - 管理引用计数和对象生命周期的模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2467879/

10-13 06:37