首页 > 解决方案 > 如何在 C# 中使用等待异步进程?

问题描述

我的代码有问题。我有启动器和自动更新。我想解压缩过程等待下载,但我不能这样做。你能帮助我吗 ?

嗨,我的代码有问题。我有启动器和自动更新。我想解压缩过程等待下载,但我不能这样做。你能帮助我吗 ?

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

等待 - 异步下载问题

标签: c#async-await

解决方案


DownFile是一种async void方法。调用这样的方法称为“一劳永逸”,因为您没有机会确定异步操作何时完成。事实上,async void除了事件处理程序之外,您几乎从不想使用。而是async Task用于不返回值的异步操作。在您的情况下,您有一个完美的例子,何时使用async void以及何时使用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;
}

推荐阅读