gpt4 book ai didi

c# - 如何使用 webclient 异步下载多个文件,但一次下载一个文件?

转载 作者:IT王子 更新时间:2023-10-29 04:24:14 25 4
gpt4 key购买 nike

很难找到使用 webclient 类异步方法下载多个文件但一次下载一个的代码示例。

如何启动异步下载,但要等到第一个下载完成,直到第二个下载完成,等等。基本上是一个问题。

(注意我不想使用同步方法,因为异步方法增加了功能。)

下面的代码立即开始我所有的下载。 (进度条到处都是)

private void downloadFile(string url)
{
WebClient client = new WebClient();

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

// Starts the download
btnGetDownload.Text = "Downloading...";
btnGetDownload.Enabled = false;
progressBar1.Visible = true;
lblFileName.Text = url;
lblFileName.Visible = true;
string FileName = url.Substring(url.LastIndexOf("/") + 1,
(url.Length - url.LastIndexOf("/") - 1));
client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);

}

void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{

}

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}

最佳答案

我所做的是填充一个包含我所有 url 的队列,然后我下载队列中的每个项目。当没有剩余元素时,我可以处理所有元素。我在下面模拟了一些代码。请记住,下面的代码用于下载字符串而不是文件。修改以下代码应该不会太困难。

    private Queue<string> _items = new Queue<string>();
private List<string> _results = new List<string>();

private void PopulateItemsQueue()
{
_items.Enqueue("some_url_here");
_items.Enqueue("perhaps_another_here");
_items.Enqueue("and_a_third_item_as_well");

DownloadItem();
}

private void DownloadItem()
{
if (_items.Any())
{
var nextItem = _items.Dequeue();

var webClient = new WebClient();
webClient.DownloadStringCompleted += OnGetDownloadedStringCompleted;
webClient.DownloadStringAsync(new Uri(nextItem));
return;
}

ProcessResults(_results);
}

private void OnGetDownloadedStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null && !string.IsNullOrEmpty(e.Result))
{
// do something with e.Result string.
_results.Add(e.Result);
}
DownloadItem();
}

编辑:我已经修改了您的代码以使用队列。不完全确定您希望进展如何运作。我敢肯定,如果您希望进度满足所有下载的需求,那么您可以将项目计数存储在“PopulateItemsQueue()”方法中,并在进度更改方法中使用该字段。

    private Queue<string> _downloadUrls = new Queue<string>();

private void downloadFile(IEnumerable<string> urls)
{
foreach (var url in urls)
{
_downloadUrls.Enqueue(url);
}

// Starts the download
btnGetDownload.Text = "Downloading...";
btnGetDownload.Enabled = false;
progressBar1.Visible = true;
lblFileName.Visible = true;

DownloadFile();
}

private void DownloadFile()
{
if (_downloadUrls.Any())
{
WebClient client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;

var url = _downloadUrls.Dequeue();
string FileName = url.Substring(url.LastIndexOf("/") + 1,
(url.Length - url.LastIndexOf("/") - 1));

client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);
lblFileName.Text = url;
return;
}

// End of the download
btnGetDownload.Text = "Download Complete";
}

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
// handle error scenario
throw e.Error;
}
if (e.Cancelled)
{
// handle cancelled scenario
}
DownloadFile();
}

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}

关于c# - 如何使用 webclient 异步下载多个文件,但一次下载一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com