可以使用异步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)
}我猜人们需要一个自定义的调度器之类的,但这是可能的吗?(也就是说,它是否可以用于递归,而不是清除调用堆栈)
发布于 2011-04-15 04:11:56
是的,这是完全可能的。
在最新的异步CTP ( VS2010 SP1刷新)中,单元测试示例中有一个"GeneralThreadAffineContext“类(无论是在VB中还是在C#中)。这提供了以通用线程仿射方式运行异步方法所需的助手代码。
通过线程关联,我们的意思是异步延续在与原始线程相同的上下文中处理,类似于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); });
}https://stackoverflow.com/questions/5668065
复制相似问题