8
I am developing a client/server communication, and using Task
for asynchronous communication.
Previously, I had already made another communication where I used Thread
, works smoothly and consumes little processing.
In that now with Task
I had a high processing, and it did not seem to happen the Delay between iterations of while
. I decided to change all the Task.Delay
for Thread.Sleep
.
And the result was satisfactory. It started to have the delay at each iteration and the CPU consumption remained low.
Here is the question:
What’s the difference between Task.Delay()
and Thread.Sleep()
Code snippet where a
TcpListener
accepts the connections (This part is within the execution of aTask
):
while (_running)
{
if (server.Pending())
{
TcpClient client = server.AcceptTcpClient();
string nIP = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
ChatServerClient clie = new ChatServerClient(++_idControl, client, this._log);
_clients.Add(clie);
ClientConnected(new ClientChatEventArgs() { Client = clie });
clie.OnClientStop += clie_OnClientStop;
clie.StartClient();
clie.Enviar.Enqueue("Servidor Conectado.");
}
else
{
Thread.Sleep(2000); //Funciona, baixo CPU e espera o tempo
//Task.Delay(2000); //Não funciona, alto CPU e não espera o tempo
}
}
See help: https://answall.com/q/86014/101
– Maniero