2011-04-14 85 views
1

是否可以使用Async CTP來模擬延續和尾遞歸?繼續使用異步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) 
} 

我想一個人需要一個定製的調度等,但有可能? (也就是說,是否可以用於遞歸調用堆棧的w/o)

回答

4

是的,這是完全可能的。

在最新的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); }); 
} 
+0

這些擴展名位於哪裏?我已經安裝了SP1異步刷新..無法找到產量,也沒有generalthreadaffinecontext – 2011-04-15 06:39:45

+0

GeneralThreadAffineContext不是官方API的一部分 - 它實際上是單元測試示例中的一些輔助代碼。此外,爲了CTP的目的,Yield()是一種脫離TaskEx的方法,因爲我們的目標是讓CTP框架API可以部署而無需修補.NET框架。 – 2011-04-15 23:43:48