c# (连接)流读取异步无限读取 0
本文关键字:读取 异步 无限 连接 | 更新日期: 2023-09-27 18:30:41
给定以下从Stream
异步读取的方法(简化):
private async void WaitForIncomingMessagesAsync()
{
var responseStream = WebRequest.Create("some url").GetResponse().GetResponseStream(); // onle here in the example
var buffer = new byte[8192];
var stringBuilder = new StringBuilder();
while (IsRunning /*set by other parts of the program*/)
{
int receivedDataCount;
do
{
receivedDataCount = await responseStream.ReadAsync(buffer, 0, buffer.Length);
if (receivedDataCount != 0)
{
stringBuilder.Append(Encoding.ASCII.GetString(buffer, 0, receivedDataCount));
}
} while (receivedDataCount > 0);
var receivedDataJson = stringBuilder.ToString();
Array.Clear(buffer, 0, buffer.Length);
stringBuilder.Clear();
}
}
这工作正常,直到我通过流收到第一条"消息"。从那时起,它将不再停留在 await
处,因为它始终读取 0。
流本身必须始终保持开放。
我错过了什么?我是否必须重置流、刷新流或将位置设置回 0?
responseStream.Position = 0;
或responseStream.Seek(0, SeekOrigin.Begin)
抛出 NotSupportedException
根据您的代码,我想您希望每次运行外部循环时都读取新消息。如果是这样,则 GetResponse 应位于外部循环内,否则一旦内部循环完成对流的迭代,您将永远不会读取新数据。
private async void WaitForIncomingMessagesAsync()
{
var buffer = new byte[8192];
var stringBuilder = new StringBuilder();
while (IsRunning)
{
using (var responseStream = WebRequest.Create("some url").GetResponse().GetResponseStream())
{
int receivedDataCount;
do
{
receivedDataCount = await responseStream.ReadAsync(buffer, 0, buffer.Length);
if (receivedDataCount != 0)
{
stringBuilder.Append(Encoding.ASCII.GetString(buffer, 0, receivedDataCount));
}
} while (receivedDataCount > 0);
}
var receivedDataJson = stringBuilder.ToString();
Array.Clear(buffer, 0, buffer.Length);
stringBuilder.Clear();
}
}
我还将您的响应流包装成使用 (..) {} 构造,因此您不必担心手动关闭和处置它。