I have a multi-threaded application which communicates with a server over a TCP connection. The application would be deployed as a windows service.
The way it has been implemeted is, there is Controller
which creates Communicator
objects, assigns the port number, message count etc. properties to the Communicator
and invokes its StartClient
method to commence the dialog with the server.
Within the StartClient
method, each Communicator
object creates a connection to the server, using the port number and url specified by the Controller
. After establishing the connection, it internally creates a thread and calls the ReadMessages
method which keeps reading from the server till the message count is met and then gets closed down.
Based on the runtime conditions, there might be a need to reuse the Communicator
object to talk with the server again and hence, the ReadMessages
method woudl be called again.
Initially, we had been calling Dispose()
method for the NetworkStream, StreamReader and StreamWriter objects when the ReadMessages
method completed, but with the reconnecting scenario, it used to throw "Cannot access a disposed object" error. So, we commented out the Dispose
method call for testing.
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.
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?
One way to tackle this can be to create a new instance of Stream objects each time the Communicator
connects with the server, but I think that would be an expensive operation.
Can you please help me identify a better approach to handle the situation here so that I can reuse the Communicator
object without a performance hit?