我一直在尝试使用 C# 从 Twitter 流 API 读取数据,但由于有时 API 不会返回任何数据,而我正在寻找近乎实时的响应,所以我一直在犹豫是否使用更长的缓冲区读取器上超过 1 个字节,以防流在接下来的一两天内不再返回任何数据。
我一直在使用以下行:
input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null);
//buffer = new byte[1]
现在我计划扩大应用程序,我认为大小为 1 会导致大量 CPU 使用,并且想增加该数字,但我仍然不希望流只是阻塞。如果在接下来的 5 秒或类似情况下没有读取更多字节,是否可以让流返回?
最佳答案
异步选项
如果没有收到任何字节,例如,您可以在异步回调方法中使用计时器来完成操作。 5秒。每次接收到字节时重置定时器。在 BeginRead 之前启动它。
同步选项
或者,您可以使用底层套接字的 ReceiveTimeout 属性来确定在完成读取之前等待的最长时间。您可以使用更大的缓冲区并将超时设置为例如5 秒。
来自MSDN documentation该属性仅适用于同步读取。您可以在单独的线程上执行同步读取。
更新
这是从类似问题拼凑而成的未经测试的粗略代码。它可能不会按原样运行(或没有错误),但应该给你一个想法:
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();
}
关于c# - 使用 HTTP 流而不一次读取一个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13830600/