Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if I have something to read on a StreamReader?

I need to check if my client has something in the buffer so I did not wait to write it.

private async void ThreadMethod_ListenClient()
    {
        while (true) {
            if (ClientQueue.Count == 0)
                continue;
            Client client = (Client)ClientQueue.Dequeue ();
            if (client.Reader != null) {
                string Say = await client.Reader.ReadLineAsync();
                if (Say != null) {
                    if (Say.Length != 0) {
                        Console.WriteLine (Say);
                    }
                }
            }
            ClientQueue.Enqueue (client);

        }
    }

client.Reader : StreamReader from TcpClient

client.Socket : TcpClient

How to check if 'client.Reader' empty?

obs. C# with Mono

like image 275
Marlon Henry Schweigert Avatar asked Mar 13 '23 18:03

Marlon Henry Schweigert


2 Answers

Also StreamReader.Peek() which returns -1 when end of file is reached or when there's nothing to read. Can be checked as follows:

while(StreamReader.Peek() != -1){
    //Your code here
}
like image 182
Ahmed Anwar Avatar answered Apr 26 '23 05:04

Ahmed Anwar


How to check if I have something to read on a StreamReader?

I don't know for StreamReader, but for TcpClient you can use TcpClient.GetStream() method which returns NetworkStream which in turn has DataAvailable property. This is explained in the Remarks section of the TcpClient.GetStream documentation:

You can avoid blocking on a read operation by checking the DataAvailable property.

Edit: I've posted this because your code is running into a specific domain. While the general approach described in other answers/comments work for normal finite streams (like FileStream, MemoryStream etc.), it doesn't work for infinite streams like NetworkStream.

like image 20
Ivan Stoev Avatar answered Apr 26 '23 07:04

Ivan Stoev