2015-05-18 35 views
0

我試圖用固定的超時從Azure下載blob。我在.NET 4.5中有以下工作代碼。但是,當我嘗試在.NET 4.0中重寫時,我找不到指定CancellationTokenSource超時的方法。你能幫忙嗎?在C#.NET 4.0中爲異步調用指定CancellationTokenSource超時

var cts = new CancellationTokenSource((int)TimeSpan.FromSeconds(30).TotalMilliseconds); 

using (var memoryStream = new System.IO.MemoryStream()) 
{ 
    Task task = blockBlob.DownloadToStreamAsync(memoryStream, cts.Token); 
    await task.ConfigureAwait(false); 

    ... 
} 

此外,我發現下面的代碼(在4.0)超時,如果blob未在指定的時間下載。我不確定是否有任何我應該小心使用它。

Task task = blockBlob.DownloadToStreamAsync(memoryStream); 
task.Wait((int)TimeSpan.FromSeconds(30).TotalMilliseconds); 

回答

0

AFAIK無法指定4.5框架之前的CancellationTokenSource超時。我建議你用另一個方法

var cts = new CancellationTokenSource(); 
var timer = new System.Timers.Timer(timeout) {AutoReset = false}; 
timer.Elapsed += (sender, eventArgs) => { cts.Cancel(); }; 
var task = new Task(action, cts.Token); 
task.Start(); 
timer.Start(); 

笨拙,但工作

+0

謝謝!我編輯了原文,以顯示我工作的代碼。我不確定是否有什麼我應該注意的。 – Groot

相關問題