Reputation: 1501
I came across this code snippet online. However, I cannot understand how the while(true)
blocking takes place in this code:
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
Can anyone explain it to me? I know of using while(true)
+ breaking condition, but this thing is beyond me.
Upvotes: 1
Views: 862
Reputation: 6270
It's not the while(true)
that does the blocking, it's the AcceptTcpClient()
. This is what happens:
this.tcpListener.AcceptTcpClient()
is executed and the thread stops, because AcceptTcpClient is a blocking method.Upvotes: 3
Reputation: 4664
AcceptTcpClient
is what blocks. The while (true)
will just endlessly loop until the process terminates, the thread is interrupted, or an exception is thrown.
Upvotes: 5