繁体   English   中英

如何在 C# 中为 url 调用添加超时和重试?

[英]How to add timeout and retry to url call in C#?

我有一个.tgz文件,我需要在Testing文件夹中下载一个 url。 我能够使用WebClient从 url 成功下载.tgz文件。

下面是我的代码:

private void DownloadTGZFile(string url, string fileToDownload)
{
    using (var client = new WebClient())
    {
        client.DownloadFile(url + fileToDownload, "Testing/configs.tgz");
    }
}

我想看看如何在此调用中添加超时,以便如果 url 在特定时间内没有响应,那么它应该超时,但它可以重试 3 次然后放弃。 另外,我想看看如何在这里使用HttpClient而不是WebClient ,因为它是较旧的 BCL class 并且不推荐。

要使用HttpClient下载文件,您可以执行以下操作:

// Is better to not initialize a new HttpClient each time you make a request, 
// it could cause socket exhaustion
private static HttpClient _httpClient = new HttpClient()
{
    Timeout = TimeSpan.FromSeconds(5)
};

public async Task<byte[]> GetFile(string fileUrl)
{
    using (var httpResponse = await _httpClient.GetAsync(fileUrl))
    {
        // Throws an exception if response status code isn't 200
        httpResponse.EnsureSuccessStatusCode();
        return await httpResponse.Content.ReadAsByteArrayAsync();
    }
}

有关使用 HttpClient 耗尽套接字的更多详细信息

如您所见,要为Http调用定义超时,您应该在创建新的HttpClient时设置超时。


要为前面的代码实施重试策略,我将安装Polly NuGet package然后:

public async Task<byte[]> GetFile(string fileUrl)
{
    return await Policy
       .Handle<TaskCanceledException>() // The exception thrown by HttpClient when goes in timeout
       .WaitAndRetryAsync(retryCount: 3, sleepDurationProvider: i => TimeSpan.FromMilliseconds(300))
       .ExecuteAsync(async () =>
       {
           using (var httpResponse = await _httpClient.GetAsync(fileUrl))
           {
               // Throws an exception if response status code isn't 200
               httpResponse.EnsureSuccessStatusCode();
               return await httpResponse.Content.ReadAsByteArrayAsync();
           }
       });
}

在这种情况下,我定义了 3 次重试,每次尝试之间的间隔为 300 毫秒。 另请注意,我没有为每种Exception定义重试,因为如果 - 例如 - 你输入了一个无效的URL ,重试是无稽之谈。

最后,如果你想将该字节数组保存到文件中,你可以这样做:

File.WriteAllBytes(@"MyPath\file.extension", byteArray);

您可以使用此 function 而不依赖于外部库。 它适用于任何文件大小。

编辑版本以传播TaskCanceledException

public async Task<bool> DownloadFileAsync(string url,
    string destinationFile,
    TimeSpan timeout,
    int maxTries = 3,
    CancellationToken token = default)
{
    using (var client = new HttpClient { Timeout = timeout })
    {
        for (var i = 0; i < maxTries; i++, token.ThrowIfCancellationRequested())
        {
            try
            {
                var response = await client.GetAsync(url, token);
                if (!response.IsSuccessStatusCode)
                    continue;

                var responseStream = await response.Content.ReadAsStreamAsync();
                using (var outputStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write))
                {
                    await responseStream.CopyToAsync(outputStream, 8 * 1024, token);
                    return true;
                }
            }
            catch (HttpRequestException)
            {
                //ignore
            }
        }
        return false;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM