Home > Software engineering >  How do I wait for something to finish in C#?
How do I wait for something to finish in C#?

Time:01-06

 private void Download_Click(object sender, EventArgs e)
        {
            label1.Text = "Downloading...";
            WebClient wc = new WebClient();
            string program = "Program";
            string link = "https://linkhere.com";
            string download = wc.DownloadString(link);
            string path = "Program\\"   program   ".zip";
            string patch = "Program";
            Directory.CreateDirectory(patch);
            wc.DownloadFile(download, path);
            label1.Text = "Downloaded!";
        }

I want to make the label1.Text = "Downloaded!"; to happen after it downloads the program.

CodePudding user response:

You need to make the download asynchronous to prevent the deadlock.

private async void Download_Click(object sender, EventArgs e)
{
    label1.Text = "Downloading...";
    WebClient wc = new WebClient();
    string program = "Program";
    string link = "https://linkhere.com";
    string download = wc.DownloadString(link);
    string path = "Program\\"   program   ".zip";
    string patch = "Program";
    Directory.CreateDirectory(patch);
    await wc.DownloadFileAsync(download, path);
    label1.Text = "Downloaded!";
}

CodePudding user response:

The DownloadFile docs say "This method blocks while downloading the resource", so I'm not sure what could be different about your situation, or if there even is a problem.

I suspect that you never see "Downloading..." because the UI does not update in between the two label1.Text update calls. Adding Application.DoEvents() after the first .Text update may help.

  •  Tags:  
  • Related