是的,这是完全可能的。
在最新的Async CTP(Refresh for 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); });
}
这些扩展名位于哪里?我已经安装了SP1异步刷新..无法找到产量,也没有generalthreadaffinecontext – 2011-04-15 06:39:45
GeneralThreadAffineContext不是官方API的一部分 - 它实际上是单元测试示例中的一些辅助代码。此外,为了CTP的目的,Yield()是一种脱离TaskEx的方法,因为我们的目标是让CTP框架API可以部署而无需修补.NET框架。 – 2011-04-15 23:43:48