用于管理引用计数和对象寿命的模式

5 .net c# vb.net oop design-patterns

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

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


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

}
Run Code Online (Sandbox Code Playgroud)

对于连接的每个设备,我们为设备创建一个对象

  device = new Device();
  device.Attach(channel);    //this calls channel.AddReference()
Run Code Online (Sandbox Code Playgroud)

当设备断开连接时

  device.Detach(channel); //this calls channel.ReleaseReference()
Run Code Online (Sandbox Code Playgroud)

我不相信引用计数模型.有没有更好的方法来处理.NET World中的这个问题?

Jon*_*eet 5

您可以考虑将Attach返回类型实现IDisposable.这会暴露可用的端口成员,但是他们会在内部委托回原始对象(除了公开暴露之外的任何东西Attach); 调用Attach会增加引用次数; 处理返回的值会减少它.然后你就可以做到:

using (Foo foo = device.Attach(channel))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

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