Template for managing the number of links and objects

We have a serial port that is connected to hundreds of physical devices on the same cable. We have protocols, such as Modbus and Hart, for processing request and response between the application and devices. The question is about channel reference number management. When the device does not use a channel, the channel must be closed.

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

For each connected device, we create an object for the device, for example

  device = new Device(); device.Attach(channel); //this calls channel.AddReference() 

When the device turns off,

  device.Detach(channel); //this calls channel.ReleaseReference() 

I am not convinced of the reference reference model. Is there a better way to deal with this problem in .NET World?

+4
source share
2 answers

You might consider Attach returning an implementation type of IDisposable . This will result in the usable ports being used, but they will internally delegate back to the original object (which does not publicly disclose anything except Attach ); calling Attach will increase the number of links; disposal of the returned value will reduce it. Then you can:

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

One oddity to consider is that you start with a reference count of 0, but without closing the port. Should you perhaps only open it the first time you call Attach ?

+5
source

As mentioned in Jon Skeet, you should use the Disposable pattern, but as you seem to use this class in parallel environments, your increments ( ++ ) and decrements ( -- ) should be atomic using Interlocked.Increment and .Decrement .

Actually, you may need a lock() object so that you can increase and open the device when counter 1 (the second Attach can try to open the device again at the same time) and reduce and then close the device when counter 0 .

+2
source

Source: https://habr.com/ru/post/1304434/


All Articles