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:
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?
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?
Handle(socket)
ever run? – Ronelpublic async void AwaitSocket() { while (true) { var socket = await this.AcceptSocketAsync(); Handle(socket); } }
? – PepperandsaltAwaitSocket();
returns. And yes, it does return. – Pepperandsaltawait
may complete synchronously, and in that case, the order gets messed up. – Pepperandsaltawait
doesn't return very promptly? – Autobiographyawait
will contain a call back into the same method. To my eyes it doesn't look like it should return. Can you post a sample application so we can all have a play? – AutobiographyHandle
from what I can see. Unless I'm not seeing what code is run when it immediately returns as opposed to the code run when the await resolves. – Autobiographyawait
doesn't always return directly, as I mentioned in an earlier comment. It may return directly, or if the result is already available without waiting, it may process the result directly. – Pepperandsaltawait
in a method necessarily implies a return to the caller at that point. – Andriaandrianawhile
condition loop tells people to expect it to keep running while a particular condition isn't met. Recursion for while semantics, though it may work, will be difficult to read at a glance. – AutobiographyHandle()
can run concurrently. – AnastasioHandleAsync(socket)
which schedules a call toHandle(socket)
that doesn't need to run on the same thread. – Pepperandsaltasync
, I think calling anasync
method causes a new thread each time. – Undone