WebClient DownloadFileCompleted事件Lambda中await报错:如何添加async修饰符?
解决C#异步Lambda表达式的await报错问题
你遇到的错误是因为绑定DownloadFileCompleted事件的Lambda表达式中使用了await,但该Lambda未标记为异步。
解决方法
只需在Lambda的参数列表前添加async修饰符即可,修改后的事件绑定代码如下:
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(async (sender, e) => await Completed(sender, e, sw));
也可以省略显式的委托类型声明,编译器会自动推断,写法更简洁:
webClient.DownloadFileCompleted += async (sender, e) => await Completed(sender, e, sw);
修改后的完整代码
public async Task DownloadFile(string urlAddress, string location) { Stopwatch sw = new Stopwatch(); using (WebClient webClient = new WebClient()) { webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome"); // 添加async修饰符修复报错 webClient.DownloadFileCompleted += async (sender, e) => await Completed(sender, e, sw); webClient.DownloadProgressChanged += (sender, e) => ProgressChanged(sender, e, sw); Uri URL = new Uri(urlAddress); sw.Start(); try { await webClient.DownloadFileTaskAsync(URL, location); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
补充说明
这里使用async void的Lambda是合法场景——事件处理程序本身就是void返回类型的异步场景,符合C#异步编程规范。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

