You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:39:27