简体   繁体   中英

NetworkStream Pooling

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?

该方法将基于您需要阅读消息的频率而定-如果偶尔出现n,我建议您重构通讯对象以使“ ReadMessages”操作原子化-即它将连接到服务器,创建网络流,阅读消息,然后处置所有物品。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM