简体   繁体   English

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

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

I have a .tgz file that I need to download given a url inside a Testing folder.我有一个.tgz文件,我需要在Testing文件夹中下载一个 url。 I am able to download the .tgz file successfully from the url using WebClient .我能够使用WebClient从 url 成功下载.tgz文件。

Below is my code:下面是我的代码:

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

I wanted to see on how can I add a timeout to this call so that if url doesn't respond back within a particular time then it should timeout but it can retry for 3 times and then give up.我想看看如何在此调用中添加超时,以便如果 url 在特定时间内没有响应,那么它应该超时,但它可以重试 3 次然后放弃。 Also I wanted to see on how can I use HttpClient here instead of WebClient considering it is an older BCL class and not recommended.另外,我想看看如何在这里使用HttpClient而不是WebClient ,因为它是较旧的 BCL class 并且不推荐。

To download a file with HttpClient you can do:要使用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();
    }
}

For more details about socket exhaustion with HttpClient 有关使用 HttpClient 耗尽套接字的更多详细信息

As you see, to define a timeout for the Http call you should set a timeout while creating a new HttpClient .如您所见,要为Http调用定义超时,您应该在创建新的HttpClient时设置超时。


To implement a retry policy for the previous code, I would install Polly NuGet package and then:要为前面的代码实施重试策略,我将安装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();
           }
       });
}

In this case I defined a retry of 3 times with an interval of 300 milliseconds between each tentative.在这种情况下,我定义了 3 次重试,每次尝试之间的间隔为 300 毫秒。 Also note that I didn't defined the retry for every kind of Exception , because if - for example - you put an invalid URL , retrying is nonsense.另请注意,我没有为每种Exception定义重试,因为如果 - 例如 - 你输入了一个无效的URL ,重试是无稽之谈。

At the end, if you want to save that byte array to a file, you can just do:最后,如果你想将该字节数组保存到文件中,你可以这样做:

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

You can use this function with no dependencies to external libraries.您可以使用此 function 而不依赖于外部库。 It works for any file size.它适用于任何文件大小。

EDIT Version to progapate the TaskCanceledException .编辑版本以传播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