博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#使用BeginInvoke和EndInvoke异步下载和获取返回结果
阅读量:6711 次
发布时间:2019-06-25

本文共 2246 字,大约阅读时间需要 7 分钟。

场景:为了防止UI卡死,使用异步下载文件

问题:采用多线程下载,关闭窗口后下载线程不能停止,线程操作麻烦。

参考:C#客户端的异步操作:

方案:采用BeginInvoke的方式调用下载方法,委托会自动启动新线程,停止时也不需要手动控制。使用EndInvoke获取返回结果。

try{    IAsyncResult ir = process.BeginInvoke(new HttpDownloadDelegate(HttpDownload),url,path);     bool result = process.EndInvoke(ir);}catch(Exception ex){    MessageBox.Show(ex.Message);}//方法声明public delegate bool HttpDownloadDelegate(string url, string path)public bool HttpDownload(string url, string path){    //下载方法...}

 

HTTP下载:

///         /// http下载文件        ///         /// 下载文件地址        /// 文件存放地址,包含文件名        /// 
public bool HttpDownload(string url, string path) { string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp"; System.IO.Directory.CreateDirectory(tempPath); //创建临时文件目录 string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //临时文件 if (System.IO.File.Exists(tempFile)) { System.IO.File.Delete(tempFile); //存在则删除 } try { FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 //Stream stream = new FileStream(tempFile, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { //stream.Write(bArr, 0, size); fs.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } //stream.Close(); fs.Close(); responseStream.Close(); System.IO.File.Move(tempFile, path); return true; } catch (Exception ex) { return false; } }

 

转载地址:http://yfalo.baihongyu.com/

你可能感兴趣的文章
Android中经常使用的bitmap处理方法
查看>>
ffmpeg超详细综合教程——摄像头直播
查看>>
Python3在指定路径下递归定位文件中出现的字符串
查看>>
iterm2退出时保存会话状态,下次打开恢复
查看>>
关于UNPIVOT 操作符
查看>>
图片人脸检测——OpenCV版(二)
查看>>
java字符编码转换
查看>>
DPDK virtio-user
查看>>
mp3
查看>>
scrapy-redis介绍(一)
查看>>
微信公众平台开发概述
查看>>
Migrate from ASP.NET Core 2.0 to 2.1
查看>>
利用git提交代码
查看>>
Elasticsearch的Java API做类似SQL的group by聚合。
查看>>
SQL 序号列ROW_NUMBER,RANK,DENSE_RANK、NTILE
查看>>
Redis使用基本套路
查看>>
[React] Refactor a connected Redux component to use Unstated
查看>>
mac应用
查看>>
性能优化2--内存优化
查看>>
ambassador 学习六 Module说明
查看>>