C# 多次调用DownloadFileAsync
我正在申请WPF。我使用WebClient的DownloadFileAsync下载文件。我从文件夹中一次下载每个文件。我第一次调用DownloadProtocol时,它工作正常,但当我想下载一个包含新文件的新文件夹时,我再次调用DownloadProtocol,我的应用程序冻结。我希望更多的下载过程中在同一时间C# 多次调用DownloadFileAsync,c#,wpf,download,webclient,C#,Wpf,Download,Webclient,我正在申请WPF。我使用WebClient的DownloadFileAsync下载文件。我从文件夹中一次下载每个文件。我第一次调用DownloadProtocol时,它工作正常,但当我想下载一个包含新文件的新文件夹时,我再次调用DownloadProtocol,我的应用程序冻结。我希望更多的下载过程中在同一时间 foreach (var x in res) { Console.WriteLine("111");
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!");
}
}
我想一次下载一个文件
在不阻塞UI的情况下,async/await非常适合这样做。您可以编写一个方法下载文件
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);
}
}
删除
while(client.IsBusy){..}
我之所以要删除while,是因为我想从当前文件夹一次下载一个文件@因此,为什么不在循环中简单地使用async/await呢?(DownloadFileTaskAsync
)抱歉,我是线程编程新手。但有可能在foreach中使用wait吗@EserI将其作为答案发布。感谢您的回答。我尝试了你的实现,但它冻结了我的WPF应用程序@Eser@LocDaiLe很可能你做错了什么。以上代码无法阻止用户界面。这就是async/Await的全部要点,我也会说它不应该这样做,但它会这样做吗?请你看一下我的实现。刚刚更新了我的编辑。看起来很有效,但是当我下载一个文件,然后想在第一个仍在运行我的应用程序冻结/崩溃时下载另一个文件时?你在评论中说我想一次下载一个文件,所以我不理解你的评论。