I am learning some basic C# programming.
Was following a tutorial and the main function has a loop like this:
class Server
{
static List<Client> _clients = new();
static TcpListener _listener = new(IPAddress.Parse("127.0.0.1"),7892);
static void Main(string[] args)
{
_listener.Start();
while (true)
{
var client = new Client(_listener.AcceptTcpClient());
_clients.Add(client);
Console.WriteLine(_clients.Count+ " total clients");
}
}
}
Since this is an infinite never ending while loop, why does the program not hang like it does when I accidently create an infinite loop in other scripts?
Additionally, when I ran this code, I was surprised to find it was not adding a new client every loop, but only when a client connected, how exactly is it waiting on the AcceptTcpClient() function? I looked at the code for this function, its not clear to me how its waiting...
public TcpClient AcceptTcpClient()
{
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
Socket acceptedSocket = _serverSocket!.Accept();
return new TcpClient(acceptedSocket);
}