Async ctp recursion

I'm about 15 minutes into my first game with async CTP ... (nice).

Here is a really simple server I knocked down with:

internal class Server
{
    private HttpListener listener;
    public Server()
    {
        listener = new HttpListener();
        listener.Prefixes.Add("http://*:80/asynctest/");
        listener.Start();
        Go();
    }

    async void Go()
    {
        HttpListenerContext context = await listener.GetContextAsync();
        Go();
        using (var httpListenerResponse = context.Response) 
        using (var outputStream = httpListenerResponse.OutputStream) 
        using (var sw = new StreamWriter(outputStream))
        {
            await sw.WriteAsync("hello world");
        }
    }
}

As you can see, the asynchronous method Gocalls itself. In a classic non-asynchronous world, this will lead to a stack overflow. I suppose this does not apply to the asynchronous method, but I would like to be sure, anyway. Is anyone

+5
source share
1 answer

Let me add it to something simpler:

async static void Go()
{
    await Something();
    Go();
    await SomethingElse();
}

How does the compiler handle this?

It basically becomes something like this sketch:

class HelperClass
{
    private State state = STARTSTATE;
    public void DoIt()
    {

        if (state == STARTSTATE) goto START;
        if (state == AFTERSOMETHINGSTATE) goto AFTERSOMETHING;
        if (state == AFTERSOMETHINGELSESTATE) goto AFTERSOMETHINGELSE;

        START:
        {
           state = AFTERSOMETHINGSTATE;
           var awaiter = Something().MakeAnAwaiter();
           awaiter.WhenDoneDo(DoIt);
           return;
        }

        AFTERSOMETHING:
        {
           Go();
           state = AFTERSOMETHINGELSESTATE;
           var awaiter = SomethingElse().MakeAnAwaiter();
           awaiter.WhenDoneDo(DoIt);
           return;
        }

        AFTERSOMETHINGELSE:

        return;
    }

    static void Go()
    {
        var helper = new HelperClass();
        helper.DoIt();
    }

, , , , "DoIt" (, ).

? . Go . DoIt. Something(), , awaiter , awaiter " , helper1.DoIt" .

, helper1 DoIt. helper1 state AFTERSOMETHINGSTATE, goto Go. helper2 DoIt. Something(), , awaiter , awaiter " , DoIt helper2" helper1 DoIt. SomethingElse, awaiter " - , helper1 DoIt". .

. . , SomethingElse . helper1.DoIt(), . Helper1 .

helper2.DoIt() AFTERSOMETHING. Go(), helper3...

, , . , Go , Something(), . "-" . "Go" .

+13

All Articles