c# - 管理引用计数和对象生命周期的模式

标签 c# .net vb.net design-patterns oop

我们有一个串行端口,它通过同一条线路连接到数百个物理设备。我们有像 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 的类型。这将公开可用的端口成员,但他们会在内部委托(delegate)回原始对象(不会公开公开除Attach之外的任何内容);调用 Attach 会增加引用计数;处理返回值会减少它。然后你就可以:

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

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

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

相关文章:

c# - NAudio:正确使用 MixingSampleProvider 和 VolumeSampleProvider

.net - MonoTouch 中的 CLLocationDegrees 在哪里?

c# - 将参数发送到驻留在另一个进程中的应用程序实例

linux - Linux 上的 VB.NET

.net - vb.net 中的绝对值

c# - 在 wpf 用户控件中公开一个字段以供外部使用

c# - Connection was not closed, Connection's current state is open error in foreach 循环

C# 使用 LINQ 查询将记录与过程数组的结果进行比较

.net - 使用参数在 Azure 函数中调用 GET API

java - 从.net调用java命令行程序并将STDOUT的输出返回到变量