线程机制(避免卡屏),异步下载文件。

  我做网站的监控,WebClient.DownloadFile这个方法是我经常用到的,必要的时候肯定是要从网上下载些什么(WebRequest 也可以下载网络文件,不妨搜下,不过WebClient.DownloadFile使用更简单)。

  今天简单的演示下WebClient.DownloadFileAsync的使用,刚刚写好的实例,有问题你拍我。

  解释什么的都不需要了吧。这里面应用了线程机制,异步调用。wo先展示代码,在把一些关键点放置到后面,并给一些修改建议(设计器生成代码在下,可以不用看,只需要复制粘贴使用)。

测试中用到的网络文件(随机抽取.exe,.rar,.zip),都是无害的,请放心测试:

http://dl1sw.baidu.com/client/9h162/fzjqd.exe
http://sq.onlinedown.net/down/sgbs.rar
http://zj.down.chinaz.com/201408/bdswxt_v1.0.zip
http://zj.down.chinaz.com/201408/zyzfwxt_v1.1.zip

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Net;
  10. using System.Threading;
  11. using System.IO;
  12.  
  13. namespace WindowsFormsApplication1
  14. {
  15. public partial class Form1 : Form
  16. {
  17. public Form1()
  18. {
  19. InitializeComponent();
  20.  
  21. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  22. }
  23.  
  24. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  25. {
  26. File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "error.log", DateTime.Now.ToString() + "\t" + e.ExceptionObject.ToString() + Environment.NewLine);
  27. }
  28.  
  29. /// <summary>
  30. /// 文件总数
  31. /// </summary>
  32. int _totalFile = ;
  33. /// <summary>
  34. /// 已下载文件
  35. /// </summary>
  36. int _loadFile = ;
  37.  
  38. private void button1_Click(object sender, EventArgs e)
  39. {//Run
  40. string richText = richTextBox1.Text;
  41. if (string.IsNullOrEmpty(richText))
  42. {
  43. MessageBox.Show("请在文本框中输入需要下载的网络文件");
  44. }
  45.  
  46. Thread thread = new Thread(new ThreadStart(() => createWebClient(richText)));
  47. thread.Start();
  48. }
  49.  
  50. //WebClient webClient = null;
  51.  
  52. private void createWebClient(string richText)
  53. {
  54. string[] array = richText.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
  55.  
  56. _totalFile = array.Length;
  57.  
  58. foreach (string item in array)
  59. {
  60. WebClient webClient = new WebClient();
  61.  
  62. webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
  63. webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
  64.  
  65. string fileName = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToFileTimeUtc() + item.Substring(item.LastIndexOf('/') + );
  66.  
  67. webClient.DownloadFileAsync(new Uri(item), fileName);
  68.  
  69. }
  70. }
  71.  
  72. private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  73. {
  74. this.Invoke(new MethodInvoker(delegate {
  75. this.progressBar2.Value = e.ProgressPercentage;
  76. this.label2.Text = string.Format("正在下载文件,完成进度{0}% {1}/{2}(字节)"
  77. ,e.ProgressPercentage
  78. , e.BytesReceived
  79. , e.TotalBytesToReceive);
  80. }));
  81. }
  82.  
  83. private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
  84. {
  85. _loadFile++;
  86.  
  87. int percent = (int)(100.0 * _loadFile / _totalFile);
  88.  
  89. this.Invoke(new MethodInvoker(delegate {
  90. this.progressBar1.Value = percent;
  91. this.label1.Text = string.Format("已完成文件下载{0}% {1}/{2}(文件个数)"
  92. , percent
  93. , _loadFile
  94. , _totalFile);
  95. }));
  96.  
  97. if (sender is WebClient)
  98. {
  99. ((WebClient)sender).CancelAsync();
  100. ((WebClient)sender).Dispose();
  101. }
  102. }
  103.  
  104. private System.ComponentModel.IContainer components = null;
  105. protected override void Dispose(bool disposing)
  106. {
  107. if (disposing && (components != null))
  108. {
  109. components.Dispose();
  110. }
  111. base.Dispose(disposing);
  112. }
  113. private void InitializeComponent()
  114. {
  115. this.progressBar1 = new System.Windows.Forms.ProgressBar();
  116. this.progressBar2 = new System.Windows.Forms.ProgressBar();
  117. this.label1 = new System.Windows.Forms.Label();
  118. this.label2 = new System.Windows.Forms.Label();
  119. this.label3 = new System.Windows.Forms.Label();
  120. this.label4 = new System.Windows.Forms.Label();
  121. this.richTextBox1 = new System.Windows.Forms.RichTextBox();
  122. this.button1 = new System.Windows.Forms.Button();
  123. this.SuspendLayout();
  124. //
  125. // progressBar1
  126. //
  127. this.progressBar1.Location = new System.Drawing.Point(, );
  128. this.progressBar1.Name = "progressBar1";
  129. this.progressBar1.Size = new System.Drawing.Size(, );
  130. this.progressBar1.TabIndex = ;
  131. //
  132. // progressBar2
  133. //
  134. this.progressBar2.Location = new System.Drawing.Point(, );
  135. this.progressBar2.Name = "progressBar2";
  136. this.progressBar2.Size = new System.Drawing.Size(, );
  137. this.progressBar2.TabIndex = ;
  138. //
  139. // label1
  140. //
  141. this.label1.AutoSize = true;
  142. this.label1.Location = new System.Drawing.Point(, );
  143. this.label1.Name = "label1";
  144. this.label1.Size = new System.Drawing.Size(, );
  145. this.label1.TabIndex = ;
  146. this.label1.Text = "label1";
  147. //
  148. // label2
  149. //
  150. this.label2.AutoSize = true;
  151. this.label2.Location = new System.Drawing.Point(, );
  152. this.label2.Name = "label2";
  153. this.label2.Size = new System.Drawing.Size(, );
  154. this.label2.TabIndex = ;
  155. this.label2.Text = "label2";
  156. //
  157. // label3
  158. //
  159. this.label3.AutoSize = true;
  160. this.label3.Location = new System.Drawing.Point(, );
  161. this.label3.Name = "label3";
  162. this.label3.Size = new System.Drawing.Size(, );
  163. this.label3.TabIndex = ;
  164. this.label3.Text = "总 进 度:";
  165. //
  166. // label4
  167. //
  168. this.label4.AutoSize = true;
  169. this.label4.Location = new System.Drawing.Point(, );
  170. this.label4.Name = "label4";
  171. this.label4.Size = new System.Drawing.Size(, );
  172. this.label4.TabIndex = ;
  173. this.label4.Text = "当前进度:";
  174. //
  175. // richTextBox1
  176. //
  177. this.richTextBox1.Location = new System.Drawing.Point(, );
  178. this.richTextBox1.Name = "richTextBox1";
  179. this.richTextBox1.Size = new System.Drawing.Size(, );
  180. this.richTextBox1.TabIndex = ;
  181. this.richTextBox1.Text = "";
  182. //
  183. // button1
  184. //
  185. this.button1.Location = new System.Drawing.Point(, );
  186. this.button1.Name = "button1";
  187. this.button1.Size = new System.Drawing.Size(, );
  188. this.button1.TabIndex = ;
  189. this.button1.Text = "Run";
  190. this.button1.UseVisualStyleBackColor = true;
  191. this.button1.Click += new System.EventHandler(this.button1_Click);
  192. //
  193. // Form1
  194. //
  195. this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
  196. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  197. this.ClientSize = new System.Drawing.Size(, );
  198. this.Controls.Add(this.button1);
  199. this.Controls.Add(this.richTextBox1);
  200. this.Controls.Add(this.label4);
  201. this.Controls.Add(this.label3);
  202. this.Controls.Add(this.label2);
  203. this.Controls.Add(this.label1);
  204. this.Controls.Add(this.progressBar2);
  205. this.Controls.Add(this.progressBar1);
  206. this.MaximumSize = new System.Drawing.Size(, );
  207. this.MinimumSize = new System.Drawing.Size(, );
  208. this.Name = "Form1";
  209. this.Text = "WebClient下载实现实例";
  210. this.ResumeLayout(false);
  211. this.PerformLayout();
  212.  
  213. }
  214. private System.Windows.Forms.ProgressBar progressBar1;
  215. private System.Windows.Forms.ProgressBar progressBar2;
  216. private System.Windows.Forms.Label label1;
  217. private System.Windows.Forms.Label label2;
  218. private System.Windows.Forms.Label label3;
  219. private System.Windows.Forms.Label label4;
  220. private System.Windows.Forms.RichTextBox richTextBox1;
  221. private System.Windows.Forms.Button button1;
  222. }
  223. }

大致看了一下,貌似就以下几句需要新手斟酌,大神请绕行。

第一句: this.Invoke(new MethodInvoker(delegate {

第二句:Thread thread = new Thread(new ThreadStart(() => createWebClient(richText)));

第三句:if (sender is WebClient)

第一句是关键的一句,不再创建控件的线程中调用/修改控件的属性值(Text),会报异常,为什么这么用就OK了?

第二句,第三句就简单了,不提示了,不会了找度度。

本程序可以添加的功能,添加一个Stop按钮,终断下载(请不要嗤之以鼻,在创建窗体的线程里操作new Thread让其立即终断下载,还是有点深度)

WebClient.DownloadFile(线程机制,异步下载文件)的更多相关文章

  1. Web 端异步下载文件

    Web 端异步下载文件 实现文件异步下载: 在服务端无法返回文件,或发生异常时给予提示. JavaScript: 服务端返回的JSON对象形如: { code:200, msg:'下载成功|未找到指定 ...

  2. WebClient异步下载文件

    namespace ConsoleAppSyncDownload{    class Program    { static void Main(string[] args)        {     ...

  3. [c#]WebClient异步下载文件并显示进度

    摘要 在项目开发中经常会用到下载文件,这里使用winform实现了一个带进度条的例子. 一个例子 using System; using System.Collections.Generic; usi ...

  4. 使用webClient实现图片同步,异步下载

    WebClient.DownloadFile 方法 将具有指定 URI 的资源下载到本地文件. 命名空间:System.Net 程序集:System(在 system.dll 中) 同步实现参考代码: ...

  5. C# 异步下载文件

    在C#当中,利用WebClient这个核心类,可以轻易的打造一个下载器.但是这里想要强调的是,我们用的是异步操作.所谓异步,是相对于同步的概念而言的.比如Web中的Ajax就是基于异步的.它能够提供良 ...

  6. C# WebClient类上传和下载文件

    这篇文章主要介绍了C# WebClient类用法实例,本文讲解使用WebClient下载文件.OpenWriter打开一个流使用指定的方法将数据写入到uri以及上传文件示例,需要的朋友可以参考下   ...

  7. 主线程中一定不能放耗时操作,必须要开子线程,比如下载文件,不然会不让你拿到输入流--报错显示android.os.NetworkOnMainThreadException

    1.必须要开子线程来操作耗时操作,android.os.NetworkOnMainThreadException new Thread(new Runnable() { @Override publi ...

  8. js异步下载文件请求

    注意 :通常下载文件是用get请求 window.location.href=url; 但是 我们需要下载完成监听,所以必须要异步执行.用常规的ajax是不可以的.我们要用blob对象来实现1.原生的 ...

  9. android开发步步为营之67:使用android开源项目android-async-http异步下载文件

    android-async-http项目地址 https://github.com/loopj/android-async-http.android-async-http顾名思义是异步的http请求, ...

随机推荐

  1. Java学习笔记 05 数据包装类

    一.包装类 综述 >>java.lang包中的Integer类.Long类和Short类,分别将基本数据类型int.long和short封装成一个类.这些类都是Number的子类. Int ...

  2. MATLAB 画出三个通信小区cell边界示意图

    d=1000; %两个小区中心间距离的一半 rcell=2*d/sqrt(3); %小区半径 ncell=3; %小区个数 cellposition=zeros(ncell,2); %初始化小区中心位 ...

  3. mha报错

    用命令检查集群复制状态:masterha_check_repl --conf=/etc/masterha/app1.cnf 报错如下: Tue Jan 12 09:25:51 2016 - [info ...

  4. MMC不能打开文件D:\Program Files\Microsoft SQL Server\80\Tools\BINN\SQL Server Enterprise Manager.MSC

    以上问题的解决方式如下: 1. 打开windows运行对话框.在对话框输入mmc.打开了如图所示的控制台. 2. 文件---添加/删除管理单元(M). 3. 添加.然后选择Microsoft SQL ...

  5. myeclise连接oracle数据库实现登录

    package A; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatem ...

  6. 用cookie记住用户名

    有时候,我们在做登陆框时会有个复选框选择请记住我,或者有时候会遇到一些弹出框说下次不再提醒,此功能我们可以用js中的cookie实现此功能 下面记录一下如何实现该功能: 利用cookie记录用户名 1 ...

  7. VIM(四) C语言开发插件设置

    http://blog.csdn.net/guolb57/article/details/7013076

  8. Android中,图片分辨率适配总结规则drawable drawable-mdpi drawable-hdpi drawable-nodpi drawable-ldpi

    一直关于android多分辨率适配有些疑惑,从网上找到一些资料并通过测试验证,参考链接:http://blog.csdn.net/lamp_zy/article/details/7686477 现记录 ...

  9. install openvpn and openvpn manager in ubuntu

    sudo apt-get install openvpn sudo apt-get install network-manager-openvpn

  10. 张洋:浅析PageRank算法

    本文引自http://blog.jobbole.com/23286/ 很早就对Google的PageRank算法很感兴趣,但一直没有深究,只有个轮廓性的概念.前几天趁团队outing的机会,在动车上看 ...