簡體   English   中英

等待DownloadFileAsync完成下載,然后執行某些操作

[英]Wait for DownloadFileAsync to finish downloading and then do something

所以基本上我的DownloadFile是:

public void DownloadFile()
{
    settings_btn.Enabled = false;
    label1.Text = "Checking for updates...";
    //Defines the server's update directory
    string Server = "http://downloadurl/update/";

    //Defines application root
    string Root = AppDomain.CurrentDomain.BaseDirectory;

    //Make sure version file exists
    FileStream fs = null;
    if (!File.Exists("pversion"))
    {
        using (fs = File.Create("pversion")){}
        using (StreamWriter sw = new StreamWriter("pversion")){sw.Write("1.0");}
    }
    //checks client version
    string lclVersion;
    using (StreamReader reader = new StreamReader("pversion"))
    {
        lclVersion = reader.ReadLine();
    }
    decimal localVersion = decimal.Parse(lclVersion);

    //server's list of updates
    XDocument serverXml = XDocument.Load(@Server + "pUpdates.xml");

    //The Update Process
    foreach (XElement update in serverXml.Descendants("pupdate"))
    {
        string version = update.Element("pversion").Value;
        string file = update.Element("pfile").Value;

        decimal serverVersion = decimal.Parse(version);


        string sUrlToReadFileFrom = Server + file;

        string sFilePathToWriteFileTo = Root + file;

        if (serverVersion > localVersion)
        {
            using (webClient = new WebClient())
            {
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

                // The variable that will be holding the url address (making sure it starts with http://)
                Uri url = new Uri(sUrlToReadFileFrom);

                // Start the stopwatch which we will be using to calculate the download speed
                sw.Start();

                try
                {
                    // Start downloading the file
                    webClient.DownloadFileAsync(url, sFilePathToWriteFileTo);

                    // Change the currently running executable so it can be overwritten.
                    Process thisprocess = Process.GetCurrentProcess();
                    string me = thisprocess.MainModule.FileName;
                    string bak = me + ".bak";
                    if (File.Exists(bak))
                    {
                        File.Delete(bak);
                    }
                    File.Move(me, bak);
                    File.Copy(bak, me);

                    //unzip
                    using (ZipFile zip = ZipFile.Read(file))
                    {
                        foreach (ZipEntry zipFiles in zip)
                        {
                            zipFiles.Extract(Root + "\\", true);
                        }
                    }

                    //download new version file
                    webClient.DownloadFile(Server + "pversion.txt", @Root + "pversion");

                    //Delete Zip File
                    deleteFile(file);

                    var spawn = Process.Start(me);
                    thisprocess.CloseMainWindow();
                    thisprocess.Close();
                    thisprocess.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
}

我的問題是,一旦找到新版本並開始下載文件webClient.DownloadFileAsync(url, sFilePathToWriteFileTo); ,它會立即運行下面的代碼,該代碼是更改名稱,解壓縮並下載新版本文件的進度

我想要它做的就是等待它完成文件的下載,然后執行其余的工作。 我該怎么做呢?

-如果有必要,ProgressChanged:

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    label3.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00")) + " " + string.Format("{0} MB's / {1} MB's", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));;
    progressBar1.Value = e.ProgressPercentage;
    label1.Text = e.ProgressPercentage.ToString() + "%";
}

並完成:

private void Completed(object sender, AsyncCompletedEventArgs e)
{
    sw.Reset();
    if (e.Cancelled == true)
    {
        label1.Text = "Download cancelled!";
    }
    else
    {
        label1.Text = "Download completed!";
    }
}

您可以使用DownloadFile方法。 異步一詞意味着該方法將異步運行(在其他線程中),這就是為什么它立即進入下一行的原因。 如果要等待下載結束,請使用DownloadFile而不是DownloadFileAsync

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM