Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TcpClient.Available Optimizations

Is there any faster way to tell if the client has data available? I'm not saying it is slow to use TcpClient.Available, but I am curious to know if it is the fastest way.

like image 932
LunchMarble Avatar asked May 09 '26 06:05

LunchMarble


2 Answers

TcpClient.Available is not slow in itself, it just depends how you use it.

If you only use it ponctually to check if there is available data, then it is the way to go.

If you use it in a loop in order to wait for data, the overall performance of your program will be quite bad. Here is one of this bad usage:

public void Receive()
{
    while (tcpClient.Connected)
    {
        if (tcpClient.Available >= 0)
        {
            // Do something
        }
    }
}

For this second scenario, you can achieve what you want using either:

  • Asynchronous reads (look at NetworkStream.BeginRead) => most scalable
  • Blocking reads (look at the solution proposed here, which makes use of NetworkStream.Read)
like image 158
yorah Avatar answered May 12 '26 11:05

yorah


If all you need to know is whether there is data available, and you don't intend to do anything with the data, then it's probably the fastest approach.

But if you're polling to decide if there is anything to go and read, then use asynchronous I/O: start an asynchronous read operation (BeginRead) and as soon as any data arrives, you'll be called to process it. This will be much faster (and more efficient) than polling to see if there might be some data.

like image 26
Jason Williams Avatar answered May 12 '26 12:05

Jason Williams