给定以下方法从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
答案 0 :(得分:1)
根据您的代码,我想您希望每次外部循环运行时都要读取新消息。如果是这样,那么 GetResponse 应该在外部循环中,否则一旦内部循环完成对流的迭代,您将永远不会读取新数据。
h
我还将您的响应流包装到中使用(..){} 构造,因此您不必担心手动关闭和处理它。