Note that there are some explanatory texts on larger screens.

plurals
  1. POTcpClient field of abstract base class constantly being disposed
    text
    copied!<p>I have an abstract base class with a TcpClient field:</p> <pre><code>public abstract class ControllerBase { internal protected TcpClient tcpClient; </code></pre> <p>It has a method to setup a connection:</p> <pre><code>private void setupConnection(IPAddress EthernetAddress, ushort TcpPort) { if (this.tcpClient == null || !this.tcpClient.Connected) { this.tcpClient = new TcpClient(); try { this.tcpClient.Connect(EthernetAddress, TcpPort); } catch(Exception ex) { throw new TimeoutException("The device did not respond.\n" + ex.Message); } } } </code></pre> <p>And than methods to request data:</p> <pre><code> internal protected virtual byte[] requestData(IPAddress EthernetAddress, ushort TcpPort, byte[] data, bool IgnoreResponse) { setupConnection(EthernetAddress, TcpPort); //The rest of the code uses this.tcpClient </code></pre> <p>There are a few others, such as requestRawData, etc... they are required for very specific hardware communication protocols, but that's not part of this question in any way.</p> <p>I then have classes that derive from this class and they override the base class methods:</p> <pre><code>public class Controller : ControllerBase { internal virtual byte[] requestData(byte[] data, bool IgnoreResponse) { return base.requestData(this.eth0.EthernetAddress, this.eth0.TcpPort, data, IgnoreResponse); } </code></pre> <p>The code works without any exceptions, but everytime the setupConnection method is called, the TcpClient instance (tcpClient) seems to be disposed, so a new one is created and the connect method is called again, really slowing down the communication process.</p> <p>Note: Public methods of the child class call the requestData method, abstracting many details from the developer using this library.</p> <p>Such as SetDevicePower(byte PowerLevel), QueryDeviceName() etc...</p> <p>Code such as this:</p> <pre><code>Controller controller = new Controller("172.17.0.3",34000); string name = controller.QueryDeviceName(); controller.SetDevicePower(200); </code></pre> <p>causes the connect method to be called twice... why is it being disposed between calls?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload