views:

103

answers:

2

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().

A: 

No. A recursive function calls itself. Unless File.EndRead, or HandleDataReceived, or BeginAsyncRead call this function, or some other function in the call sequence, then this function is not recursive.

Michael
well I figured since this function is called from within the BeginAsyncRead and another call is placed here to BeginAsyncRead. I figured this might create another instance of the BeginAsyncRead function.
Dark Star1
In that case, yes, but these types of recursive calls: f1 --> f2 --> f3 --> f4 --> f1 are very hard to understand and debug and i'd recommend avoiding them at all cost.
Michael
+1  A: 

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.

Hans Passant