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();
}
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.
What am I doing wrong?
You’ve got a never-ending recursion.
You’re calling
ReadAsync()forever and never return from the method (hence breaking the infinite recursion).A possible solution is:
To understand recursion better, check this.