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

后端 未结 3 642
花落未央
花落未央 2021-01-02 07:21

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

相关标签:
3条回答
  • 2021-01-02 08:02

    I discovered, that if you call NetworkStream.Read with size = 0, it will actually block:

    networkstream.Read(buffer, 0, 0);
    

    The documentation is not clear about this, but for me it worked.

    0 讨论(0)
  • 2021-01-02 08:08

    The simplest way is probably to use an additional thread which reads synchronously and puts extra data onto an extra queue.

    Alternatively you could use asynchronous IO, but that's somewhat tricky - and you'd still need to have some additional queue.

    Although Socket has a Select() method (and you can get at a socket from a NetworkStream) I don't believe it exposes this functionality in a way which lets you mix it with other kinds of wait handles.

    0 讨论(0)
  • 2021-01-02 08:17

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题