3

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
LunchMarble
  • 5,079
  • 9
  • 64
  • 94
  • In what kind of usage scenario? If you have a ton of sockets and you want to know whether any of them have become readable, Socket.Select may be interesting as well. – harold Jan 04 '12 at 16:46
  • Please don't prefix your titles with "C#" and such. That's what tags are for. – John Saunders Jan 04 '12 at 16:51

2 Answers2

2

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:

Community
  • 1
  • 1
yorah
  • 2,653
  • 14
  • 24
1

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.

Jason Williams
  • 56,972
  • 11
  • 108
  • 137