暂停循环,直到下载事件完成
本文关键字:事件 下载 循环 暂停 | 更新日期: 2023-09-27 18:21:59
如何暂停someRandomMethod()中的循环,直到DownloadCompleted()中代码执行完毕?下面的代码只对版本数组中的最新版本进行解包。这就像循环比第一次下载更快,并且m_CurrentlyDownloading在第一次执行DownloadCompleted()时具有最新的值。
private void someRandomMethod() {
for (int i = 0; i < versions.Count; i++)
{
//ClearInstallFolder();
m_CurrentlyDownloading = versions.ElementAt(i);
Download(versions.ElementAt(i));
LocalUpdate(versions.ElementAt(i));
System.Threading.Thread.Sleep(500);
}
}
private void Download(string p_Version)
{
string file = p_Version + ".zip";
string url = @"http://192.168.56.5/" + file;
//client is global in the class
client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
client.DownloadFileAsync(new Uri(url), @"C:'tmp'" + file);
}
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
Unpack(m_CurrentlyDownloading);
if (GetInstalledVersion() == GetLatestVersion())
ClearZipFiles();
}
else
MessageBox.Show(e.Error.ToString());
}
最简单的方法是不使用*async
方法。正常的DownloadFile将暂停执行,直到它完成。
但是,如果您可以访问Await关键字,请尝试此操作。
private async Task Download(string p_Version)
{
string file = p_Version + ".zip";
string url = @"http://192.168.56.5/" + file;
//client is global in the class
client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
await client.DownloadFileAsync(new Uri(url), @"C:'tmp'" + file);
}
类似的东西可以用来等待
使其成为类属性
bool IsDownloadCompleted=false;
将其添加到DownloadCompletedEvent中
IsDownloadCompleted=true;
这就是你想停止循环的地方
while(DownloadCompleted!=true)
{
Application.DoEvents();
}
创建一些布尔变量,创建一个委托并为该变量获取''设置方法。然后在循环中制作smth类似:
while(!isDownLoadCompleted)Thread.Sleep(1024);
您可以使用Paralel.ForEach。此循环将等待所有线程完成。查看此处了解如何使用:http://msdn.microsoft.com/tr-tr/library/dd460720(v=vs.110).aspx或http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx