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?
This code is not thread-safe. Whatever else may be true, InternalFireQueuedAsync is racy if called by multiple threads. If one thread is running the while loop, it may reach a point at which it is empty.
Asynchronous loops are necessary when there is a large number of iterations involved or when the operations within the loop are complex. But for simple tasks like iterating through a small array, there is no reason to overcomplicate things by using a complex recursive function.
Yes. If you don't need to wait, don't wait.
with async / await , you write less code and your code will be more maintainable than using the previous asynchronous programming methods such as using plain tasks. async / await is the newer replacement to BackgroundWorker , which has been used on windows forms desktop applications.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With