流式读取等待异步

时间:2012-09-04 13:49:47

标签: c#

我编写了以下方法来从流中读取数据。在我的电脑上,它将成为一个MemoryStream,而在现实世界中,它将成为一个网络流。

    public async void ReadAsync()
    {
        byte[] data = new byte[1024];
        int numBytesRead = await _stream.ReadAsync(data, 0, 1024);

        // Process data ...

        // Read again.
        ReadAsync();
    }

这里的想法是在回调中处理数据,然后回调应该产生一个新的读取器线程(并杀死旧的)。 然而,这不会发生。我得到一个StackOverflowException。

我做错了什么?

3 个答案:

答案 0 :(得分:11)

你有一个永无止境的recursion

你永远在调用ReadAsync()并且永远不会从方法返回(因此打破了无限递归)。

可能的解决方案是:

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();
    }
}

更好地理解递归,check this

答案 1 :(得分:7)

此处没有直接涉及的主题(请参阅async / await的简介。)

你的StackOverflowException是由于递归太深而引起的(通常是这样)。只需重新编写要迭代的方法:

public async Task ReadAsync()
{
  byte[] data = new byte[1024];

  while (true)
  {
    int numBytesRead = await _stream.ReadAsync(data, 0, 1024);
    if (numBytesRead == 0)
      return;

    // Process data ...
  }
}

答案 2 :(得分:2)

您至少需要检查流中是否有数据,重复操作或递归永不停止

// Read again.
if(numBytesRead != 0)
    ReadAsync();