2012-01-09 78 views
3

如何將接受回調函數的現有異步方法作爲參數包裝進任務並行庫兼容方法?將現有的異步方法包裝爲TPL兼容方法

// Existing method 
void DoAsync(Action<string> callback) { 
    ... 
} 

// The desired method should have similar prototype 
Task<string> DoAsync() { 
    // Internally this method should call existing 
    // version of DoAsync method (see above) 
} 

回答

3

我假設您現有的DoAsync方法將異步運行。

在這種情況下,你可以用它像這樣:

Task<string> DoAsyncTask() 
{ 
    var tcs = new TaskCompletionSource<string>(); 
    DoAsync(result => tcs.TrySetResult(result)); 
    return tcs.Task; 
} 

我沒有看到你的現有DoAsync方法如何報告異步錯誤。如有必要,您可以使用TaskCompletionSource<T>.TrySetException報告異步錯誤。

+0

謝謝,究竟需要什麼,看起來相當不錯! – sam 2012-01-09 17:21:26