-2

i have problem with my code. I have launcher and auto updates. i want unzip proccess wait the download but i cant do it. Can you help me ?

Hi, i have problem with my code. I have launcher and auto updates. i want unzip proccess wait the download but i cant do it. Can you help me ?

async void DownFile(string savep, string url)
{
    using (WebClient webClient = new WebClient())
    {
        webClient.UseDefaultCredentials = true;
        webClient.DownloadProgressChanged += client_DownloadProgressChanged;
        webClient.DownloadFileCompleted += client_DownloadFileCompleted;
        await webClient.DownloadFileTaskAsync(new Uri(url), savep);
    }   
}

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Download In Process";
    DownFile(savep, url);
    label1.Text = "unzip";

    Program.ExtractZipFile(savep, "", Application.StartupPath);

    button1.Enabled = false;
}

Await - Async Download Problem

  • i just need to waiting the downFile function. if i do it with non Async its working. – Selcuk Mollaibrahimoğlu Jan 13 '19 at 22:56
  • @Daniel A. White I disagree with the duplicate flag. In Both questions the Execption is the same, but in this case the question is how to wait for the download operation to prevent that exception. The cause of the exception is known by the op – Pretasoc Jan 13 '19 at 23:11

1 Answers1

0

DownFile is an async void Method. Calling such a method is called fire and forget, because you have no chance to determine when the asynchronous operation finished. In fact you almost never want to use async void except in the case of event handlers. Instead use async Task for asynchronous operations that don't return a value. In your case you have a perfect example when to use async void and when async Task.

async Task DownFile(string savep, string url)
{
    using (WebClient webClient = new WebClient())
    {
        webClient.UseDefaultCredentials = true;
        webClient.DownloadProgressChanged += client_DownloadProgressChanged;
        webClient.DownloadFileCompleted += client_DownloadFileCompleted;
        await webClient.DownloadFileTaskAsync(new Uri(url), savep);
    }   
}

private async void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Download In Process";
    await DownFile(savep, url);
    label1.Text = "unzip";

    Program.ExtractZipFile(savep, "", Application.StartupPath);

    button1.Enabled = false;
}
Pretasoc
  • 1,116
  • 12
  • 22