我们有一个串行端口,它通过同一条线路连接到数百个物理设备。我们有像 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/