Pattern for managing reference count and object life

Posted by Gopalakrishnan Subramani on Stack Overflow See other posts from Stack Overflow or by Gopalakrishnan Subramani
Published on 2010-03-18T06:26:22Z Indexed on 2010/03/18 6:31 UTC
Read the original article Hit count: 334

We have a serial port which is connected to hundreds of physical devices on the same wire. We have protocols like Modbus and Hart to handle the request and response between the application and devices. The question is related to managing the reference count of the channel. When no device is using the channel, the channel should 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 device connected, we create a object for the device like

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

When the device disconnect,

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

I am not convinced by the reference count model. Are there any better way to handle this problem in .NET World?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#