你如何等待一个网络流有数据读取? [英] How do you wait for a Network Stream to have data to read?

查看:208
本文介绍了你如何等待一个网络流有数据读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中的工作线程,负责三个不同的东西。对于两个作业中,我已经写了队列调高的要求,其他工作是当一个请求变成了一个网络流激活。我想我的工作线程等待,没有做工作的时候。因为它们暴露被设置时,他们有项目,然而的NetworkStream似乎不具有此一ManualResetEvent的,这是很容易与两个队列。该的NetworkStream已从一个TcpClient的检索

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
    }
}



有谁知道一种方式来获得时的NetworkStream具有数据设置一个WaitHandle的?

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

推荐答案

您可以使用的NetworkStream的异步方法和坐落在EndReceive方法的ManualResetEvent。

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
    }
}

这篇关于你如何等待一个网络流有数据读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆