简体   繁体   中英

How to use Wait async process in c#?

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM