I'm developing client / server communication, and using Task
for asynchronous communication.
Previously, I had already made another communication where I used Thread
, works without problems and consumes little processing.
In this now with Task
I had a high processing, and seemed to not happen the Delay between iterations of while
. I have decided to change all Task.Delay
to Thread.Sleep
.
And the result was satisfactory. It started to have the delay at each iteration and the CPU consumption remained low.
Here's the question:
What is the difference between Task.Delay()
and Thread.Sleep()
Code snippet where
TcpListener
accepts connections (This snippet 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
}
}