HttpClient 图像文件不是未完全下载 c#

HttpClient Image file is not is not fully downloaded c#

我有这个代码:

for(int i = 0; i< Alim(exo).Count; i++)
             {
                APIResource a = new APIResource();
                a = Alim(exo)[i];
              
                object test;
                if (!_cache.TryGetValue(a.name, out test))
                {
                    
                    _cache.Set(a.name, a.name);
                  
                    //System.Threading.Thread.Sleep(2000);
                    using (var httpClient = new HttpClient())
                    {
                        using (var request = new HttpRequestMessage(HttpMethod.Get, Alim(exo)[i].url))
                        {
                            using (
                                Stream contentStream = await (await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
                                stream = new FileStream(Path.Combine(specificFolder, Alim(exo)[i].name), FileMode.Create, FileAccess.ReadWrite))
                            {
                                await contentStream.CopyToAsync(stream);
                                
                            }
                        }
                    }

                    MessageBox.Show("coucou");
                    
                }
                exo[i].ThumbnailLocalPath = @"secretpath" + a.name;
             }

但是我的图片没有完全下载看截图:

为了让它工作,我必须把 thread.sleep.

我也试过 Webclient.DownloadFile

我的函数是Async.

谢谢。

<html> <head><title>429 Too Many Requests</title></head> <body> <center><h1>429 Too Many Requests</h1></center> <hr><center>openresty</center> </body> </html>

所以 429 正是我的情况 talking about,根据服务器的配置和响应,您在太短的时间内发出了太多请求。

如果他们很慷慨,他们会附上 Retry-After 回复 header。否则你将不得不重试(最好使用 exponential backoff,即 1.x、2.x、4.x、...秒,其中 x 是随机的毫秒数)直到你成功了。

为此,您应该先保存并检查响应:

var response = await httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
    // wait, then retry
}

另外,不要处理 HttpClient,在您的应用程序生命周期内重复使用它。