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