CaTx
CaTx

Reputation: 1501

while(true) blocking

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

Answers (2)

System Down
System Down

Reputation: 6270

It's not the while(true) that does the blocking, it's the AcceptTcpClient(). This is what happens:

  1. tcpListener is started.
  2. The loop is started (since true is always true)
  3. this.tcpListener.AcceptTcpClient() is executed and the thread stops, because AcceptTcpClient is a blocking method.
  4. If a connection request is made the block goes away and a TcpClient is returned as the variable client.
  5. A new thread is created for client
  6. The loop goes back again to AcceptTcpClient and stops there until a new connection is made.

Upvotes: 3

Fls'Zen
Fls'Zen

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

Related Questions