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

相关推荐
垂葛酒肝汤5 分钟前
C#的const和static的问题
开发语言·c#
xb113232 分钟前
WinForms 多窗体应用程序详解
数据库·microsoft·c#
xb11321 小时前
C# WinForms界面设计
开发语言·c#
阿蒙Amon3 小时前
C#每日面试题-简述类成员
开发语言·c#
阿蒙Amon3 小时前
C#每日面试题-ValueTuple和Tuple的区别
开发语言·c#
_守一3 小时前
UE5.2 C++插件中调用C#第三方库
c++·ue5·c#
闻缺陷则喜何志丹3 小时前
【C# WPF】TextBox的数据绑定
ui·c#·wpf·mvvm·数据绑定·textbox
我是苏苏15 小时前
C#高级:使用ConcurrentQueue做一个简易进程内通信的消息队列
java·windows·c#
Never_Satisfied17 小时前
C#获取汉字拼音字母方法总结
开发语言·c#
不绝1911 天前
C#核心:多态
开发语言·c#