How do you wait for a Network Stream to have data to read?

Martin Brown picture Martin Brown · Sep 1, 2009 · Viewed 10.6k times · Source

I have a worker thread in my application that is responsible for three different things. Requests for two of the jobs turn up in Queues that I have written, the other job is activated when a request turns up on a Network stream. I would like my worker thread to wait when there is no work to be done. This is easy with the two Queues as they expose a ManualResetEvent that is set when they have items, however the NetworkStream does not seem to have this. The NetworkStream has been retrieved from a TcpClient.

What I am after is code that looks something like this:

while (notDone)
{
    WaitHandle.WaitAny(new WaitHandle[] { queue1.HasData, queue2.HasData, netStream.HasData } );
    // ...
    if (netStream.DataAvailable)
    {
        netStream.Read(buffer, 0, 20);
        // process buffer
    }
}

Does anyone know a way to get a WaitHandle that is set when a NetworkStream has data?

Answer

HasaniH picture HasaniH · Sep 1, 2009

You can use the async methods of the NetworkStream and set a ManualResetEvent in the EndReceive method.

// ...
netStream.BeginRead(buffer, offset, callback, state);
// ...

inside the callback method

netStream.EndRead(ar);
netStreamManualResetEvent.Set();

then your code

while (notDone)
{
    WaitHandle.WaitAny(new WaitHandle[] { queue1.HasData, queue2.HasData, netStreamManualResetEvent} );
    // ...
    if (netStream.DataAvailable)
    {
        // make the buffer from the AsyncState in the callback method available here
        // process buffer
    }
}