C# 吃一堑,长一智

Webclient DownloadDataCompleted不能回调

C# 里的WebClient,我曾经尝试使用webClient.DownloadDataCompleted += (se, ev) =>{}

进行接收文件,但是却不能触发,因为我使用了autoResetEvent进行同步线程,耗时一天,以为是异步的问题,发现没听劝,webclient只适用于.net3,弃用了。使用httpClient进行接收流文件。

httpClient使用C#.NET HttpClient 使用教程 - 我是唐青枫 - 博客园

cs 复制代码
public class WebAccess
{
    public Action? DownloadPrograssChanged;
    public Action? DownloadCompleted;

    public async Task DownloadAsync(FileModel fileModel, string localFileName,TotalProgress totalProgress)
  {
    
    using (var httpClient = new HttpClient())
    {
        DownloadCompleted += () =>
        {
            fileModel.State = "已更新";
        };

        DownloadPrograssChanged = new Action(() =>
        {
            //total_file_read = (long)(total_file_read / 1024);
            totalProgress.Progress = (int)((totalProgress.TotalReadKByte * 100) / totalProgress.TotalKByte);
            if (totalProgress.Progress >= 99)
            {
                totalProgress.Progress = 100;
            }
        });
       
        // 下载进度回调需要自己实现(HttpClient没有现成的Progress事件)
        using (var response = await httpClient.GetAsync(new Uri($"http://localhost:5003/api/file/download/{fileModel.FileName}"), HttpCompletionOption.ResponseHeadersRead))
        {
            //response.EnsureSuccessStatusCode();
            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("服务器获取更新文件异常");
            }
            var totalBytes = response.Content.Headers.ContentLength ?? 0;
            using (var stream = await response.Content.ReadAsStreamAsync())
            {

                using (var fileStream = new FileStream(localFileName, FileMode.Create))
                {
                    var buffer = new byte[8192];//8kb
                    long totalRead = 0;
                    int read;
                    while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        await fileStream.WriteAsync(buffer, 0, read);
                        totalRead += read;
                        if (totalBytes > 0)
                        {
                            var progress = (int)((totalRead * 100) / totalBytes);
                            fileModel.Progress = progress;
                            totalProgress.TotalReadKByte += (read / 1024);
                            DownloadPrograssChanged?.Invoke();
                        }
                    }
                }
            }
        }
        
    }
    DownloadCompleted?.Invoke();
  }
}

异步函数同步之后捕获不了异常

一定要加GetResult

webDataAccess.DownloadAsync(fi, localFileName, FileTotalProgress).GetAwaiter().GetResult();

相关推荐
雪隐11 小时前
WPF + MVVM 实战系列01-一个老狗回炉重造 WPF 的 12 天血泪史
sqlite·c#·mvvm
在世修行12 小时前
从零打造 C# 工业视觉检测系统(四):海康威视 MVS SDK 入门与相机枚举实战
数码相机·c#·视觉检测
神秘的MT13 小时前
C# WinForm Socket 服务器 + 串口转发
服务器·网络·学习·c#
czhc114007566317 小时前
8.4:今日概念与语法总结
c#
大数据张老师17 小时前
Typora 导出 Word 模版操作手册
开发语言·c#·word·typora
我是苏苏18 小时前
C#基础:使用System.Speech.Synthesis离线播放/朗读文字内容
开发语言·c#
程序员-Benothing20 小时前
如何实现高并发系统订单30分钟自动关闭?
开发语言·c#·wpf
海盗12341 天前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
dalong102 天前
WPF:3D甜甜圈
3d·c#·wpf·甜甜圈
神秘的MT2 天前
C# WinForm Socket 类 常用方法 (C# .NET,TCP 场景)
服务器·网络·学习·tcp/ip·c#·winform