Reputation: 412
I have a TcpListener listening for incoming connections, and now i basically want to ask if it is better to process the client communication in the same thread or start a new one; so if there is a best practice.
I intentionally didn't add the try-catch blocks and other handling to keep the question simple and clear.
Method 1:
while(true)
{
TcpClient client = listener.AcceptTcpClient();
processData(client);
}
Method 2:
while(true)
{
TcpClient client = listener.AcceptTcpClient();
new Thread(() => processData(client)).Start();
}
Method 3:
while(true)
{
TcpClient client = listener.AcceptTcpClient();
Thread t = new Thread(() => processData(client));
t.Start();
t.Join();
}
The code was written like Method 1 before, but processData
randomly threw ThreadAbortException
s, which shut down the entire server thread (probably because of some timeout with the client, could not exactly find the source of the Exception as the code runs on a .NET Compact framework on an Embedded Compact 2013 machine).
Upvotes: 0
Views: 6621
Reputation: 988
i basically want to ask if it is better to process the client communication in the same thread or start a new one; so if there is a best practice.
When you are using threads with sockets you could block the I/O channels each time that the thread which handle the socket is paused. And, your first case is better than third case, because you the program doesn't need to change of thread.
So, in my experience, the best way to process multiple socket is using a single thread and its asyncrhonous methods. It is faster and secure than multiple threads by sockets. With this technic you are optimize the machine resources and avoid the threads competing for them.
Check my answer to see how to use asynchronous methods into the socket. In this case I attended 15k socket request by hour and the the use of the processor does not exceed 1%.
Upvotes: 1