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
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
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With