暂停循环直到下载事件完成

时间:2014-09-16 12:09:12

标签: c#

如何在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());
}

4 个答案:

答案 0 :(得分:3)

最简单的方法是不使用*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);
}

答案 1 :(得分:0)

这样的东西可以用来等待

使它成为类属性

      bool IsDownloadCompleted=false;

DownloadCompletedEvent

中添加此内容
      IsDownloadCompleted=true;

这就是你要停止循环的地方

   while(DownloadCompleted!=true)
  {
     Application.DoEvents();
   }

答案 2 :(得分:0)

创建一些布尔变量,为该变量创建委托并获取\ set方法。 然后就像在循环中那样做了:

while(!isDownLoadCompleted)Thread.Sleep(1024);

答案 3 :(得分:0)

您可以使用Parallel.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