继续使用异步CTP

| 是否可以使用Async CTP来模拟连续性和尾部递归? 我正在考虑以下方面的想法:
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)
}
我猜一个人需要一个自定义的调度程序,但是有可能吗? (也就是说,它可以用于递归不浪费调用堆栈)     
已邀请:
是的,这完全有可能。 在最新的异步CTP(对于VS2010 SP1刷新)中,单元测试示例(在VB或C#中)有一个\“ GeneralThreadAffineContext \”类。这提供了仅以通用线程仿射方式运行异步方法所必需的帮助程序代码。 通过线程亲和力,我们的意思是异步延续在与原始线程相同的上下文中得到处理,类似于WinForms / WPF的行为,但是没有使真正的WPF或WinForms消息循环变得混乱。
Task.Yield()
的设计是将当前方法的其余部分推迟到SynchronizationContext,因此您甚至不需要编写自己的
await ClearCallStack()
。相反,您的样本将归结为:
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); });
}
    

要回复问题请先登录注册