public void threadPoolTestFunction(Object param) { try { TcpClient tcpClient = (TcpClient)param; NetworkStream networkStream = tcpClient.GetStream(); byte[] receivedByteArray = new byte[200]; //Reading request from the stream int bytesRead = 0; bytesRead = networkStream.Read(receivedByteArray, 0, receivedByteArray.Length); if (bytesRead <= 0) { return; } //Decoding request string request = Encoding.UTF8.GetString(receivedByteArray, 0, bytesRead); //Getting the request from the database and the updating the database. SQLTest sqlTest = new SQLTest(); string response = sqlTest.select(request); sqlTest.update(request, response); sqlTest.close(); //Sending the response back to the client. byte[] sendByteArray = Encoding.UTF8.GetBytes(response); networkStream.Write(sendByteArray, 0, sendByteArray.Length); //Closing network stream networkStream.Flush(); networkStream.Close(); Console.WriteLine(" ==> " + request); Console.WriteLine(" <== " + response); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void threadPoolTestFunction(Object param) { try { string request; string response; SqlConnection sqlConnection; TcpClient tcpClient; int threadIndex = (int)param; //Sql Connection string connString = ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString; using (sqlConnection = new SqlConnection(connString)) { sqlConnection.Open(); SQLTest sqlTest = new SQLTest(sqlConnection); while (true) { Console.WriteLine("Thread " + threadIndex + " waiting for signal to start"); //Waiting for signal to start. threadStart[threadIndex].WaitOne(); //Getting the current assigned client. variableLock.WaitOne(); tcpClient = threadClients[threadIndex]; variableLock.Set(); NetworkStream networkStream = tcpClient.GetStream(); //Reading request from the cilent. byte[] receivedByteArray = new byte[200]; int bytesRead = 0; bytesRead = networkStream.Read(receivedByteArray, 0, receivedByteArray.Length); if (bytesRead <= 0) { return; } request = Encoding.UTF8.GetString(receivedByteArray, 0, bytesRead); Console.WriteLine(" ==> " + request); //Updating database with the response response = sqlTest.select(request); sqlTest.update(request, response); Thread.Sleep(10000); //Sending response back to the client. byte[] sendByteArray = Encoding.UTF8.GetBytes(response); networkStream.Write(sendByteArray, 0, sendByteArray.Length); //Closing network networkStream.Flush(); networkStream.Close(); variableLock.WaitOne(); //Resetting event so the thread waits for the new client. threadStart[threadIndex].Reset(); //Thread is available again. threadAvailability[threadIndex].Set(); variableLock.Set(); Console.WriteLine("Thread " + threadIndex + " completed the task"); Console.WriteLine(" <== " + response); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }