c# - 如何在 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;
}
等待 - 异步下载问题
解决方案
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;
}
推荐阅读
- java - 为什么当我们有自定义实现时,Java 不强制我们重写 equals 和 hashcode
- rust - 有没有一种优雅的方式来使用“match”语句重写获取或创建选项?
- css - 语义 UI 响应式
- c - 无法处理包含多个单词的单个句子。但一切似乎都还好
- hibernate - 未解决 - org.hibernate.id.enhanced.SequenceStyleGenerator.generate
- matlab - 在 Matlab 中执行此矩阵运算是否有更高效的方法
- c++ - 线程测试之间的延迟:Linux 裸机与 VM 上的 QNX
- c - 为什么我不能通过设置 PWD 来设置当前工作目录
- node.js - Node.js mongoose 无法在 MongoDB 数据库上“保存()”文档
- python - 为什么在迭代集合时添加和删除集合时会得到这么多迭代?