WebClient.DownloadFile(线程机制,异步下载文件)
线程机制(避免卡屏),异步下载文件。
我做网站的监控,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
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Threading;
- using System.IO;
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
- }
- static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
- {
- File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "error.log", DateTime.Now.ToString() + "\t" + e.ExceptionObject.ToString() + Environment.NewLine);
- }
- /// <summary>
- /// 文件总数
- /// </summary>
- int _totalFile = ;
- /// <summary>
- /// 已下载文件
- /// </summary>
- int _loadFile = ;
- private void button1_Click(object sender, EventArgs e)
- {//Run
- string richText = richTextBox1.Text;
- if (string.IsNullOrEmpty(richText))
- {
- MessageBox.Show("请在文本框中输入需要下载的网络文件");
- }
- Thread thread = new Thread(new ThreadStart(() => createWebClient(richText)));
- thread.Start();
- }
- //WebClient webClient = null;
- private void createWebClient(string richText)
- {
- string[] array = richText.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
- _totalFile = array.Length;
- foreach (string item in array)
- {
- WebClient webClient = new WebClient();
- webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
- webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
- string fileName = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToFileTimeUtc() + item.Substring(item.LastIndexOf('/') + );
- webClient.DownloadFileAsync(new Uri(item), fileName);
- }
- }
- private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
- {
- this.Invoke(new MethodInvoker(delegate {
- this.progressBar2.Value = e.ProgressPercentage;
- this.label2.Text = string.Format("正在下载文件,完成进度{0}% {1}/{2}(字节)"
- ,e.ProgressPercentage
- , e.BytesReceived
- , e.TotalBytesToReceive);
- }));
- }
- private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
- {
- _loadFile++;
- int percent = (int)(100.0 * _loadFile / _totalFile);
- this.Invoke(new MethodInvoker(delegate {
- this.progressBar1.Value = percent;
- this.label1.Text = string.Format("已完成文件下载{0}% {1}/{2}(文件个数)"
- , percent
- , _loadFile
- , _totalFile);
- }));
- if (sender is WebClient)
- {
- ((WebClient)sender).CancelAsync();
- ((WebClient)sender).Dispose();
- }
- }
- private System.ComponentModel.IContainer components = null;
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- private void InitializeComponent()
- {
- this.progressBar1 = new System.Windows.Forms.ProgressBar();
- this.progressBar2 = new System.Windows.Forms.ProgressBar();
- this.label1 = new System.Windows.Forms.Label();
- this.label2 = new System.Windows.Forms.Label();
- this.label3 = new System.Windows.Forms.Label();
- this.label4 = new System.Windows.Forms.Label();
- this.richTextBox1 = new System.Windows.Forms.RichTextBox();
- this.button1 = new System.Windows.Forms.Button();
- this.SuspendLayout();
- //
- // progressBar1
- //
- this.progressBar1.Location = new System.Drawing.Point(, );
- this.progressBar1.Name = "progressBar1";
- this.progressBar1.Size = new System.Drawing.Size(, );
- this.progressBar1.TabIndex = ;
- //
- // progressBar2
- //
- this.progressBar2.Location = new System.Drawing.Point(, );
- this.progressBar2.Name = "progressBar2";
- this.progressBar2.Size = new System.Drawing.Size(, );
- this.progressBar2.TabIndex = ;
- //
- // label1
- //
- this.label1.AutoSize = true;
- this.label1.Location = new System.Drawing.Point(, );
- this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(, );
- this.label1.TabIndex = ;
- this.label1.Text = "label1";
- //
- // label2
- //
- this.label2.AutoSize = true;
- this.label2.Location = new System.Drawing.Point(, );
- this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(, );
- this.label2.TabIndex = ;
- this.label2.Text = "label2";
- //
- // label3
- //
- this.label3.AutoSize = true;
- this.label3.Location = new System.Drawing.Point(, );
- this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(, );
- this.label3.TabIndex = ;
- this.label3.Text = "总 进 度:";
- //
- // label4
- //
- this.label4.AutoSize = true;
- this.label4.Location = new System.Drawing.Point(, );
- this.label4.Name = "label4";
- this.label4.Size = new System.Drawing.Size(, );
- this.label4.TabIndex = ;
- this.label4.Text = "当前进度:";
- //
- // richTextBox1
- //
- this.richTextBox1.Location = new System.Drawing.Point(, );
- this.richTextBox1.Name = "richTextBox1";
- this.richTextBox1.Size = new System.Drawing.Size(, );
- this.richTextBox1.TabIndex = ;
- this.richTextBox1.Text = "";
- //
- // button1
- //
- this.button1.Location = new System.Drawing.Point(, );
- this.button1.Name = "button1";
- this.button1.Size = new System.Drawing.Size(, );
- this.button1.TabIndex = ;
- this.button1.Text = "Run";
- this.button1.UseVisualStyleBackColor = true;
- this.button1.Click += new System.EventHandler(this.button1_Click);
- //
- // Form1
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(, );
- this.Controls.Add(this.button1);
- this.Controls.Add(this.richTextBox1);
- this.Controls.Add(this.label4);
- this.Controls.Add(this.label3);
- this.Controls.Add(this.label2);
- this.Controls.Add(this.label1);
- this.Controls.Add(this.progressBar2);
- this.Controls.Add(this.progressBar1);
- this.MaximumSize = new System.Drawing.Size(, );
- this.MinimumSize = new System.Drawing.Size(, );
- this.Name = "Form1";
- this.Text = "WebClient下载实现实例";
- this.ResumeLayout(false);
- this.PerformLayout();
- }
- private System.Windows.Forms.ProgressBar progressBar1;
- private System.Windows.Forms.ProgressBar progressBar2;
- private System.Windows.Forms.Label label1;
- private System.Windows.Forms.Label label2;
- private System.Windows.Forms.Label label3;
- private System.Windows.Forms.Label label4;
- private System.Windows.Forms.RichTextBox richTextBox1;
- private System.Windows.Forms.Button button1;
- }
- }
大致看了一下,貌似就以下几句需要新手斟酌,大神请绕行。
第一句: this.Invoke(new MethodInvoker(delegate {
第二句:Thread thread = new Thread(new ThreadStart(() => createWebClient(richText)));
第三句:if (sender is WebClient)
第一句是关键的一句,不再创建控件的线程中调用/修改控件的属性值(Text),会报异常,为什么这么用就OK了?
第二句,第三句就简单了,不提示了,不会了找度度。
本程序可以添加的功能,添加一个Stop按钮,终断下载(请不要嗤之以鼻,在创建窗体的线程里操作new Thread让其立即终断下载,还是有点深度)
WebClient.DownloadFile(线程机制,异步下载文件)的更多相关文章
- Web 端异步下载文件
Web 端异步下载文件 实现文件异步下载: 在服务端无法返回文件,或发生异常时给予提示. JavaScript: 服务端返回的JSON对象形如: { code:200, msg:'下载成功|未找到指定 ...
- WebClient异步下载文件
namespace ConsoleAppSyncDownload{ class Program { static void Main(string[] args) { ...
- [c#]WebClient异步下载文件并显示进度
摘要 在项目开发中经常会用到下载文件,这里使用winform实现了一个带进度条的例子. 一个例子 using System; using System.Collections.Generic; usi ...
- 使用webClient实现图片同步,异步下载
WebClient.DownloadFile 方法 将具有指定 URI 的资源下载到本地文件. 命名空间:System.Net 程序集:System(在 system.dll 中) 同步实现参考代码: ...
- C# 异步下载文件
在C#当中,利用WebClient这个核心类,可以轻易的打造一个下载器.但是这里想要强调的是,我们用的是异步操作.所谓异步,是相对于同步的概念而言的.比如Web中的Ajax就是基于异步的.它能够提供良 ...
- C# WebClient类上传和下载文件
这篇文章主要介绍了C# WebClient类用法实例,本文讲解使用WebClient下载文件.OpenWriter打开一个流使用指定的方法将数据写入到uri以及上传文件示例,需要的朋友可以参考下 ...
- 主线程中一定不能放耗时操作,必须要开子线程,比如下载文件,不然会不让你拿到输入流--报错显示android.os.NetworkOnMainThreadException
1.必须要开子线程来操作耗时操作,android.os.NetworkOnMainThreadException new Thread(new Runnable() { @Override publi ...
- js异步下载文件请求
注意 :通常下载文件是用get请求 window.location.href=url; 但是 我们需要下载完成监听,所以必须要异步执行.用常规的ajax是不可以的.我们要用blob对象来实现1.原生的 ...
- android开发步步为营之67:使用android开源项目android-async-http异步下载文件
android-async-http项目地址 https://github.com/loopj/android-async-http.android-async-http顾名思义是异步的http请求, ...
随机推荐
- Java学习笔记 05 数据包装类
一.包装类 综述 >>java.lang包中的Integer类.Long类和Short类,分别将基本数据类型int.long和short封装成一个类.这些类都是Number的子类. Int ...
- MATLAB 画出三个通信小区cell边界示意图
d=1000; %两个小区中心间距离的一半 rcell=2*d/sqrt(3); %小区半径 ncell=3; %小区个数 cellposition=zeros(ncell,2); %初始化小区中心位 ...
- mha报错
用命令检查集群复制状态:masterha_check_repl --conf=/etc/masterha/app1.cnf 报错如下: Tue Jan 12 09:25:51 2016 - [info ...
- MMC不能打开文件D:\Program Files\Microsoft SQL Server\80\Tools\BINN\SQL Server Enterprise Manager.MSC
以上问题的解决方式如下: 1. 打开windows运行对话框.在对话框输入mmc.打开了如图所示的控制台. 2. 文件---添加/删除管理单元(M). 3. 添加.然后选择Microsoft SQL ...
- myeclise连接oracle数据库实现登录
package A; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatem ...
- 用cookie记住用户名
有时候,我们在做登陆框时会有个复选框选择请记住我,或者有时候会遇到一些弹出框说下次不再提醒,此功能我们可以用js中的cookie实现此功能 下面记录一下如何实现该功能: 利用cookie记录用户名 1 ...
- VIM(四) C语言开发插件设置
http://blog.csdn.net/guolb57/article/details/7013076
- Android中,图片分辨率适配总结规则drawable drawable-mdpi drawable-hdpi drawable-nodpi drawable-ldpi
一直关于android多分辨率适配有些疑惑,从网上找到一些资料并通过测试验证,参考链接:http://blog.csdn.net/lamp_zy/article/details/7686477 现记录 ...
- install openvpn and openvpn manager in ubuntu
sudo apt-get install openvpn sudo apt-get install network-manager-openvpn
- 张洋:浅析PageRank算法
本文引自http://blog.jobbole.com/23286/ 很早就对Google的PageRank算法很感兴趣,但一直没有深究,只有个轮廓性的概念.前几天趁团队outing的机会,在动车上看 ...