gpt4 book ai didi

c# - 多次调用 DownloadFileAsync

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:19 26 4
gpt4 key购买 nike

我正在制作一个 WPF 应用程序。我使用 WebClient 的 DownloadFileAsync 下载文件。我一次从文件夹中下载每个文件。我第一次调用 DownloadProtocol 它工作正常,但是当我想下载一个包含新文件的新文件夹时,我再次调用 DownloadProtocol 我的应用程序卡住了。我希望同时进行更多下载。

            foreach (var x in res)

{
Console.WriteLine("111");
await DownloadProtocol("http://cdn.something.com/rental/" + torrentId + "/" + x, savePath + torrentId + "/" + x);

}

public async Task DownloadProtocol(string address, string location)
{

Uri Uri = new Uri(address);
using (WebClient client = new WebClient())
{
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
await client.DownloadFileTaskAsync(Uri, location);
}
/*while (client.IsBusy)
{
DoEvents();
}*/
}

public void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
public object ExitFrame(object f)
{
((DispatcherFrame)f).Continue = false;

return null;
}

private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled == true)
{
Console.WriteLine("Download has been canceled.");
}
else
{

Console.WriteLine("Download completed!");
}
}

最佳答案

i want to download one file at a time

在不阻塞您的 UI 的情况下,async/await 非常适合这种情况。你可以写一个方法 DownloadFile

public async Task DownloadFile(string url, string fileName)
{
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += (o, e) =>
{
//Console.WriteLine(e.BytesReceived);
};
await client.DownloadFileTaskAsync(url, filename);
}
}

像这里一样使用它

async void SomeClickHandler()
{
var urls = new string[] {
"http://google.com","http://stackoverflow.com"
};

foreach(var url in urls)
{
await DownloadFile(url, filename);
}
}

关于c# - 多次调用 DownloadFileAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32139790/

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