物流与阅读的await异步 [英] Stream reading with await async
问题描述
我写了下面的方法从一般流中读取数据。在我的电脑上它会是一个MemoryStream,而在现实世界中,这会是一个网络流。
I have written the following method to read data from a stream in general. On my computer it's gonna be a MemoryStream, and in the real world, it's gonna be a network stream.
public async void ReadAsync()
{
byte[] data = new byte[1024];
int numBytesRead = await _stream.ReadAsync(data, 0, 1024);
// Process data ...
// Read again.
ReadAsync();
}
这里的想法是,数据获取在回调处理,回调应然后生成一个新的阅读器线程(和杀老)。
然而,这并不发生。我得到一个StackOverflowException。
The idea here is that data gets processed in the callback, and the callback should then spawn a new reader-thread (and kill the old). This does not happen however. I get a StackOverflowException.
我在做什么错了?
推荐答案
您已经有了一个永无止境的递归。
You've got a never-ending recursion.
您正在呼叫 ReadAsync()
永远不会从方法(因此打破了无限递归)返回
You're calling ReadAsync()
forever and never return from the method (hence breaking the infinite recursion).
一个可能的解决方案是:
A possible solution is:
public async void ReadAsync()
{
byte[] data = new byte[1024];
int numBytesRead = await _stream.ReadAsync(data, 0, 1024);
// Process data ...
// Read again.
if(numBytesRead > 0)
{
ReadAsync();
}
}
要了解递归更好的检查这个
这篇关于物流与阅读的await异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!