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();

相关推荐
烛阴1 小时前
不只是Public与Private:C#访问修饰符全方位解读
前端·c#
秋雨雁南飞2 小时前
c# 多项目编译发布
c#
张人玉3 小时前
C#Https协议相关知识点
开发语言·https·c#
Byron Loong3 小时前
【C#】VS调试——带参调试
开发语言·c#
故事不长丨3 小时前
解锁C#编程秘籍:封装、继承、多态深度剖析
开发语言·数据库·c#
努力小周3 小时前
基于STM32物联网智能老年人防摔系统
stm32·单片机·嵌入式硬件·物联网·c#·课程设计
FuckPatience4 小时前
C# 补码
开发语言·算法·c#
烽火聊员4 小时前
SSLSocket 服务器端WPF C#测试代码
开发语言·c#·wpf·ssl
wangnaisheng5 小时前
【C#】RESTful的使用
c#
缺点内向5 小时前
如何在 C# 中高效的将 XML 转换为 PDF
xml·后端·pdf·c#·.net