title: NetworkStream Pooling
body: <p>I have a multi-threaded application which communicates with a server over a TCP connection. The application would be deployed as a windows service.</p>
  
  <p>The way it has been implemeted is, there is <code>Controller</code> which creates <code>Communicator</code> objects, assigns the port number, message count etc. properties to the <code>Communicator</code> and invokes its <code>StartClient</code> method to commence the dialog with the server. </p>
  
  <p>Within the <code>StartClient</code> method, each <code>Communicator</code> object creates a connection to the server, using the port number and url specified by the <code>Controller</code>. After establishing the connection, it internally creates a thread and calls the <code>ReadMessages</code> method which keeps reading from the server till the message count is met and then gets closed down. </p>
  
  <p>Based on the runtime conditions, there might be a need to reuse the <code>Communicator</code> object to talk with the server again and hence, the <code>ReadMessages</code> method woudl be called again. </p>
  
  <p>Initially, we had been calling <code>Dispose()</code> method for the NetworkStream, StreamReader and StreamWriter objects when the <code>ReadMessages</code> method completed, but with the reconnecting scenario, it used to throw <em>"Cannot access a disposed object"</em> error. So, we commented out the <code>Dispose</code> method call for testing. </p>
  
  <p>As of now, it works fine, but I am concerned that, this isnt the best way to achieve this functionlity as I am not disposing the objects ever. </p>
  
  <p>I was thinking in terms of object pooling, If it is possible to have a pool of Stream objects which could be reused by different threads?</p>
  
  <p>One way to tackle this can be to create a new instance of Stream objects each time the <code>Communicator</code> connects with the server, but I think that would be an expensive operation.</p>
  
  <p>Can you please help me identify a better approach to handle the situation here so that I can reuse the <code>Communicator</code> object without a performance hit?</p>