Search code examples
c#socketsasync-ctp

Is async recursion safe in C# (async ctp/.net 4.5)?


In C# with async ctp or the vs.net 2011 beta we can write recursive code like this:

public async void AwaitSocket()
{
    var socket = await this.AcceptSocketAsync(); //await socket and >>return<< to caller
    AwaitSocket(); //recurse, note that the stack will never be deeper than 1 step since await returns..
    Handle(socket); // this will get called since "await" returns
}

In this specific sample, the code async waits for a tcp socket and once it has been accepted, it will recurse and async wait for another one.

This seems to work fine, since the await section will make the code return to the caller and thus, not cause a stack overflow.

So two questions here:

  1. if we ignore the fact we are dealing with sockets in this sample. Is it OK to do stack free recursion this way? or are there drawbacks Im missing?

  2. from an IO perspective, would the above code be enough to handle all incoming requests? I mean by just waiting for one, and once it is accepted start waiting for another one. Will some requests fail because of this somehow?


Solution

  • From the discussion above, I guess something like this will be the best approach. Please give feedback

    public async void StartAcceptingSockets()
    {
        await Task.Yield(); 
        // return to caller so caller can start up other processes/agents
        // TaskEx.Yield in async ctp , Task.Yield in .net 4.5 beta
    
        while(true)
        {
            var socket = await this.AcceptSocketAsync();
            HandleAsync(socket); 
            //make handle call await Task.Yield to ensure the next socket is accepted as fast 
            //as possible and dont wait for the first socket to be completely handled
        } 
    }
    
    private async void HandleAsync(Socket socket)
    {
          await Task.Yield(); // return to caller
    
          ... consume the socket here...
    }