I am trying to learn async/await
so this may sound like a dumb question, but I am currently working on a basic TCP server and trying to use async/await
instead of manual threading to handle multiple connections.
In a NetworkClient
class I have the following method:
public async Task Start()
{
using (var reader = new StreamReader(_socket.GetStream()))
{
while (_server.IsRunning)
{
try
{
var content = await reader.ReadLineAsync().ConfigureAwait(false);
if (content == null)
{
Console.WriteLine("Client {0} disconnected", _id);
return;
}
Console.WriteLine("Client {0} wrote: {1}", _id, content);
}
catch (IOException)
{
Console.WriteLine("Client {0} disconnected", _id);
return;
}
}
}
}
My loop that listens for client connections contains the following code:
private void ListenForClients()
{
var numClients = 0;
while (IsRunning)
{
var tcpClient = _listener.AcceptTcpClient();
var netClient = new NetworkClient(this, tcpClient, numClients);
netClient.Start();
Console.WriteLine("Client {0} Connected", numClients);
numClients++;
}
}
This works as I expect it, allowing multiple telnet connections to connect and send messages to the server at the same time. However, resharper tells me that I should be adding await
to netClient.Start();
because otherwise it won't block. However, I do not want it to block!
The fact that Resharper is giving me a warning like this makes me wonder if I am approaching the async/await
system incorrectly. Why does Resharper want me to add await
to this line of code, and what is the correct way to work with this so that netClient.Start();
does not block other tcp connections from joining?