I have read several discussion on the matter and managed to understand a bit, but still having some issues solving the performance problem when converting from Thread class to ThreadPool class
Details:
I have build a tcp server, with educational purpose(the task should not be with async methods), which is accepting client connections and create a new thread for each client. With this method the application is executed for less than a second, but when decided to move to a next level solution like thread pool my performance dropped to 40-50 seconds for just a hundred clients and i just send a 2048 byte buffer, receive it and close.
The first 12 threads are very fast, most probably because my cpu is 6 cores 12 threaded and after that the threads start to experience a delay. I am open to solution ideas and structure approach.
Server code:
public void OnSocketReceive()
{
while (!this.exitServer)
{
if (!tcpListener.Pending())
{
Thread.Sleep(10);
continue;
}
TcpClient client = tcpListener.AcceptTcpClient();
IManageConnectedUser chatLogic = new ManageConnectedUser(connections, welcomeMessage);
//Thread clientThread = new Thread(new ParameterizedThreadStart(chatLogic.OnClientConnection));
//clientThread.Start(client);
ThreadPool.QueueUserWorkItem(chatLogic.OnClientConnection, client);
}
More clarification
By far with the debugging I have done and the discussions I have read I made the conclusion that the problem is the blocking code in OnClientConnection function and more specifically in the inner function which is stringCreateHandler. Where i receive this error: System.Threading.ThreadInterruptedException: Thread was interrupted from a waiting state on line 39, which is the Thread.Sleep(10);
public string stringCreateHandler(TcpClient client)
{
StringBuilder sb = new StringBuilder();
try
{
do
{
if (client.Available > 0)
{
while (client.Available > 0)
{
char ch = (char)client.GetStream().ReadByte();
if (ch == '\r')
{
continue;
}
if (ch == '\n')
{
return sb.ToString();
}
sb.Append(ch);
}
}
Thread.Sleep(10);
} while (true);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
I have checked the rest of the code i don't think there is more blocking code, but i am giving a link to the project https://github.com/nikolaymih/Chat-Project/tree/master/ChatProjectNewThreads The only difference there is the Thread class instead of ThreadPool but this is just for orientation