首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用异步CTP的延续

使用异步CTP的延续
EN

Stack Overflow用户
提问于 2011-04-15 02:45:25
回答 1查看 1.1K关注 0票数 1

可以使用异步CTP来模拟延续和尾递归吗?

我在想一些类似的事情:

代码语言:javascript
复制
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)
}

我猜人们需要一个自定义的调度器之类的,但这是可能的吗?(也就是说,它是否可以用于递归,而不是清除调用堆栈)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-15 04:11:56

是的,这是完全可能的。

在最新的异步CTP ( VS2010 SP1刷新)中,单元测试示例中有一个"GeneralThreadAffineContext“类(无论是在VB中还是在C#中)。这提供了以通用线程仿射方式运行异步方法所需的助手代码。

通过线程关联,我们的意思是异步延续在与原始线程相同的上下文中处理,类似于WinForms/WPF的行为,但不会启动真正的WPF或WinForms消息循环。

Task.Yield()的设计是将当前方法的其余部分推迟到SynchronizationContext,因此您甚至不需要编写自己的await ClearCallStack()

代码语言:javascript
复制
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); });
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5668065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档