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

相关推荐
q***82918 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
hixiong12310 小时前
C# OpenCVSharp实现Hand Pose Estimation Mediapipe
开发语言·opencv·ai·c#·手势识别
baivfhpwxf202311 小时前
SQL Server 服务端如何在其他电脑连接
c#
Dm_dotnet11 小时前
WPF/C#:使用Microsoft Agent Framework框架创建一个带有审批功能的终端Agent
c#
Dm_dotnet12 小时前
WPF/C#:使用Stylet中的IWindowManager用于显示等待窗体、对话框与消息框
c#
Jackson@ML12 小时前
360度看C#编程语言
开发语言·c#
wnety12 小时前
C#开发winform调用软键盘
c#·winform
谢大旭13 小时前
iframe 三档预览模式
c#
她说彩礼65万13 小时前
C# Sqlite帮助类
jvm·sqlite·c#