开发者

Continuations using Async CTP

Is it possible to use Async CTP to emulate continuations and tail 开发者_如何学运维recursion?

I'm thinking something along the lines of:

async Task Loop(int count)
{
    if (count == 0)
        retrun;

    await ClearCallStack();
    //is it possible to continue here with a clean call stack?
    Loop(count -1)
}

I guess one needs a custom scheduler and such, but would it be possible? (that is, can it be used to recurse w/o blowing the call stack)


Yes, this is entirely possible.

In the newest Async CTP (Refresh for VS2010 SP1), there's a "GeneralThreadAffineContext" class in the Unit Testing sample (either in VB or C#). That provides the requisite helper code for just running an async method in a general purpose thread-affine manner.

By thread affinity, we mean that the async continuations get processed on the same context as the original thread, similarly to the behavior for WinForms/WPF, but without spinning up the real WPF or WinForms message loop.

Task.Yield()'s design is to defer the rest of the current method to the SynchronizationContext, so you don't even need to write your own await ClearCallStack(). Instead, your sample will boil down to:

async Task DoLoop(int count)
{
    // yield first if you want to ensure your entire body is in a continuation
    // Final method will be off of Task, but you need to use TaskEx for the CTP
    await TaskEx.Yield();

    if (count == 0)
        return;

    //is it possible to continue here with a clean call stack?
    DoLoop(count -1)
}

void Loop(int count)
{
    // This is a stub helper to make DoLoop appear synchronous. Even though
    // DoLoop is expressed recursively, no two frames of DoLoop will execute
    // their bodies simultaneously
    GeneralThreadAffineContext.Run(async () => { return DoLoop(count); });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜