I’m writing an asynchronous read callback function and as I’m learning C# at the moment would like to ask if the following is recursive (It’s not mine but mine will be similar is construct):
protected void ReadCompleted(IAsyncResult iResult)
{
byte[] byIn = (byte[])iResult.AsyncState;
try
{
File.EndRead(iResult);
try
{
HandleDataReceived(byIn);
}
finally
{
BeginAsyncRead(); //recursion??
}
}
catch (IOException ioexc)
{
// Device has been removed!
}
}
Now I’m not particularly against recursion but I like to avoid it when writing something with the potential for huge memory consumption.
this whole function itself is called from within BeginAsync().
Yes, it is possible. An asynchronous operation can complete synchronously, that’s why the IAsyncResult interface has the CompletedSynchronously property. Whether that would ever cause a problem in your program is a bit hard to guess, there isn’t enough context in your snippet.
One thing you don’t have to worry about is memory, you’re not consuming any more if it completely synchronously. The worry would be if you have enough stack space. Your ReadCompleted call back will be called again while your BeginAsyncRead() method is still executing. All I can say is that it is extremely unlikely you’ll get a StackOverflowException. I never heard of anybody suffering from this problem.
Whatever device you are reading from will run out of data in its buffers before you run out of stack space. There are few devices that can do this in the first place, I only know of sockets. Maybe the file system, but you’d rarely use async I/O on that.