使用HTTP流而不一次读取一个字节

Hen*_*ang 7 .net c# asp.net stream

我一直在尝试使用C#从Twitter流API中读取数据,并且因为有时API不会返回任何数据,我正在寻找近实时响应,我一直犹豫是否使用超过1个字节的缓冲区长度如果流不会在下一天或两天返回任何更多数据,则在读取器上.

我一直在使用以下行:

input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null); 
//buffer = new byte[1]
Run Code Online (Sandbox Code Playgroud)

现在我计划扩展应用程序,我认为大小为1将导致大量的CPU使用,并希望增加该数量,但我仍然不希望流只是阻塞.如果在接下来的5秒内没有读取更多的字节或类似的东西,是否可以让流返回?

Eri*_* J. 4

异步选项

如果 5 秒内没有收到任何字节,您可以在异步回调方法中使用计时器来完成操作。每次收到字节时重置计时器。在 BeginRead 之前启动它。

同步选项

或者,您可以使用底层套接字的 ReceiveTimeout 属性来确定完成读取之前等待的最长时间。您可以使用更大的缓冲区并将超时设置为例如 5 秒。

MSDN 文档来看,该属性仅适用于同步读取。您可以在单独的线程上执行同步读取。

更新

这是根据类似问题拼凑而成的未经测试的粗糙代码。它可能不会按原样运行(或没有错误),但应该给您这样的想法:

private EventWaitHandle asyncWait = new ManualResetEvent(false);
private Timer abortTimer = null;
private bool success = false;

public void ReadFromTwitter()
{
    abortTimer = new Timer(AbortTwitter, null, 50000, System.Threading.Timeout.Infinite);

    asyncWait.Reset();
    input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null);
    asyncWait.WaitOne();            
}

void AbortTwitter(object state)
{
    success = false; // Redundant but explicit for clarity
    asyncWait.Set();
}

void InputReadComplete()
{
    // Disable the timer:
    abortTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
    success = true;
    asyncWait.Set();
}
Run Code Online (Sandbox Code Playgroud)