I am trying to download a file from Azure blob, but in 0.1% cases it just hangs at the blockBlob.DownloadToStream(...) for more than 10 mins. Is there a way I can timeout this function in 2 mins?
k!
答案 0 :(得分:8)
您可以配置整个DownloadToStream操作的超时。例如,您可以将MaximumExecutionTime设置为120秒(这适用于整个DownloadToStream操作),ServerTimeout设置为30秒(这适用于每个REST调用),并指定RetryPolicy({ {3}}或ExponentialRetry,这适用于每个REST调用),以便在请求超时或失败时启用重试。通过这样做,每个单独的LinearRetry REST调用将在服务器端限制为30秒(如果遇到服务器超时问题,重试策略将生效),并且整个DownloadToStream操作将在客户端限制为2分钟。
请参阅下面的代码示例。注意:Get Blob对象只需构造一次,然后您可以将它用于下面所有与blob相关的操作。
var maxRetryCount = 3;
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
var blobRequestOptions = new BlobRequestOptions
{
ServerTimeout = TimeSpan.FromSeconds(30),
MaximumExecutionTime = TimeSpan.FromSeconds(120),
RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(3), maxRetryCount),
};
using (var memoryStream = new MemoryStream())
{
blockBlob.DownloadToStream(memoryStream, null, blobRequestOptions);
}
答案 1 :(得分:2)
谢谢!我还得到了以下代码,以便在超时后重试下载blob。
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
var cts = new CancellationTokenSource((int)TimeSpan.FromSeconds(30 * (retryCount + 1)).TotalMilliseconds);
using (var memoryStream = new System.IO.MemoryStream())
{
Task task = blockBlob.DownloadToStreamAsync(memoryStream, cts.Token);
await task.ConfigureAwait(false);
if (!task.IsCanceled && !task.IsFaulted)
{
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
else if (task.IsCanceled)
{
retryCount++;
Console.WriteLine("Task cancelled happened for blob: {0}. Increasing timeout to: {1} sec", blobName, retryCount * 30);
}
}