Reputation: 1225
I have programmed a TCP Client in C# with write and read functionality and all is working as expected on a single thread within a command line program.
The TCP server supports a maximum of 4 connections per user/ip address and I have been informed that it's better to make use of all 4 connections in 4 threads to improve and optimise performance. The reason for this is because the software I have written is performance critical and operates on intervals of just a 100 milliseconds.
Is this correct? Should I make use of all four connections and if so what is the best way to approach this over using a single TCP client?
Edit: Sorry what I meant was the write/read operation to the tcp server happens every 100 milliseconds. The actual response is obviously much much faster, a millisecond or less.
Many thanks in advance, Dave
Upvotes: 0
Views: 201
Reputation: 663
Much of the answer depends on the hardware and the specific conditions of both the client and server - if the server is on a single core system and only handles requests in serial anyway then you will see no benefit. If however it is a quad core server and each server slot is offloaded into a separate core then you will see benefit as each request can be handled in parallel (assuming each server connection isn't also fighting for a shared resource on the server doing whatever it does).
As to the best approach, this also somewhat depends on what you're doing - if you have a scenario whereby each client gets a result that it writes to some shared resource you will have to ensure you properly handle this, for example, by creating a lock around the code that writes to the shared resource:
object lock = new object();
lock(lock)
{
// write to the shared resource
}
If each client does it's own independent thing with no access to shared resources then you have no shared resource you need to protect.
You could simply create a new instance of your client class and execute some function against it as you go, passing a parameter if you need to (here we pass the integer i as a parameter to the run function of the TestClient class such that client.Run(i) is executed against 4 separate client classes all in separate threads):
for (int i = 0; i < 4; i++)
{
TestClient client = new TestClient();
Thread thread = new Thread(new ParameterizedThreadStart(client.Run));
thread.Start(i);
}
If your TestClient.Run(int i) class method then just establishes the connection and makes the call, then does what it needs to do with any response then this should work just fine.
Hope this helps.
Upvotes: 1