0

I am trying to download a blob from Azure with a fixed timeout. I have the following working code in .NET 4.5. But, when I try to rewrite in .NET 4.0, I could not find a way to specify the timeout for CancellationTokenSource. Can you please help?

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);

    ...
}

Additionally, I found the following code (in 4.0) to timeout if the blob is not downloaded in the specified time. I am not sure if there is anything I should be careful in using it.

Task task = blockBlob.DownloadToStreamAsync(memoryStream);
task.Wait((int)TimeSpan.FromSeconds(30).TotalMilliseconds);
Groot
  • 311
  • 4
  • 15

1 Answers1

2

AFAIK no way to specify CancellationTokenSource timeout prior to 4.5 framework. I suggest you use next approach

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();

Clumsy, but working

Taukita
  • 178
  • 10
  • Thanks! I edited the original post to show the code that I got working. I am not sure if there is anything I should be careful about. – Groot May 18 '15 at 22:35