一个简单的利用 WebClient 异步下载的示例(一)
继上一篇文章 一个简单的利用 HttpClient 异步下载的示例 ,我们知道不管是 HttpClient,还算 WebClient,都不建议每次调用都 new HttpClient,或 new WebClient,而应该尽量重复对象,可以把一个 WebClient(或 HttpClient)理解成一个浏览器,不能没打开一个页面以后,就销毁它,再重新创建一个,这样会有性能损失,而建议一个线程共用一个 WebClient(或 HttpClient)。这一次,我们利用 WebClient 来实现异步下载,这一次,我们增加一个进度条来显示进度。
直接提代码了:
1. TaskDemo101
优化后的 TaskDemo101 类:
public static class TaskDemo101
{
public static string GetRandomUrl()
{
string url1 = "http://www.xxx.me/Uploads/image/20130129/2013012920080761761.jpg";
string url2 = "http://www.xxx.me/Uploads/image/20121222/20121222230686278627.jpg";
string url3 = "http://www.xxx.me/Uploads/image/20120606/20120606222018461846.jpg";
string url4 = "http://www.xxx.me/Uploads/image/20121205/20121205224383848384.jpg";
string url5 = "http://www.xxx.me/Uploads/image/20121205/20121205224251845184.jpg"; string resultUrl;
int randomNum = new Random().Next(, );
switch (randomNum)
{
case : resultUrl = url1; break;
case : resultUrl = url2; break;
case : resultUrl = url3; break;
case : resultUrl = url4; break;
case : resultUrl = url5; break;
default: throw new Exception("");
}
return resultUrl;
} public static string GetSavedFileFullName()
{
string targetFolderDestination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "downloads\\images\\");
try
{
Directory.CreateDirectory(targetFolderDestination);
}
catch (Exception)
{
Console.WriteLine("创建文件夹失败!");
}
string targetFileDestination = Path.Combine(targetFolderDestination, string.Format("img_{0}.png", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")));
return targetFileDestination;
} public static async Task<bool> RunByHttpClient(SkyHttpClient skyHttpClient, int id)
{
var task = skyHttpClient.DownloadImage(GetRandomUrl());
return await task.ContinueWith<bool>(t => {
File.WriteAllBytes(GetSavedFileFullName(), t.Result);
return true;
});
} public static void RunByWebClient(WebClient webClient, int id)
{
webClient.DownloadFileAsync(new Uri(GetRandomUrl()), GetSavedFileFullName());
}
}
2. Form1
这一次我们的 Form1 实现了 INotifyPropertyChanged 接口
public partial class Form1 : Form, INotifyPropertyChanged
{
#region 字段、属性 public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
WebClient webc = new WebClient();
bool _canChange = true;
public bool CanChange
{
get
{
return _canChange;
}
set
{
_canChange = value;
OnPropertyChanged("CanChange");
}
} #endregion public Form1()
{
InitializeComponent();
webc.DownloadFileCompleted += Webc_DownloadFileCompleted; //注册下载完成事件
webc.DownloadProgressChanged += Webc_DownloadProgressChanged; //注册下载进度改变事件
} private List<int> GetDownloadIds()
{
List<int> ids = new List<int>();
for (int i = ; i <= ; i++)
{
ids.Add(i);
}
return ids;
} private void WhenAllDownloading()
{
this.listBoxLog.Items.Insert(, string.Format("当前时间:{0},准备开始下载...", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
//禁用按钮
EnableOrDisableButtons(false);
} private void EnableOrDisableButtons(bool enabled)
{
this.btnRunByHttpClient.Enabled = enabled;
this.btnRunByWebClient.Enabled = enabled;
} private void WhenSingleDownloaded(int id, bool singleDownloadSuccess)
{
this.listBoxLog.Items.Insert(, string.Format("当前时间:{0},编号 {1} 下载 {2}!", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), id, singleDownloadSuccess));
} private void WhenAllDownloaded()
{
this.listBoxLog.Items.Insert(, string.Format("当前时间:{0},下载完毕!", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
//启用按钮
EnableOrDisableButtons(true);
} private async void btnRunByHttpClient_Click(object sender, EventArgs e)
{
SkyHttpClient skyHttpClient = new SkyHttpClient();
try
{
WhenAllDownloading();
foreach (var id in GetDownloadIds())
{
bool singleDownloadSuccess = await TaskDemo101.RunByHttpClient(skyHttpClient, id);
WhenSingleDownloaded(id, singleDownloadSuccess);
}
WhenAllDownloaded();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Download Error!");
}
} private void btnRunByWebClient_Click(object sender, EventArgs e)
{
if (CanChange)
{
WhenAllDownloading();
CanChange = false; ToDownload.Clear();
foreach (var id in GetDownloadIds())
{
ToDownload.Enqueue(id);
} progressBar1.Maximum = ToDownload.Count * ;
btnRunByWebClient.Text = "用 WebClient 暂停下载"; int firstId = ToDownload.Dequeue();
TaskDemo101.RunByWebClient(webc, firstId);
WhenSingleDownloaded(firstId, true);
}
else
{
ToDownload.Clear();
webc.CancelAsync();
CanChange = true;
progressBar1.Value = ;
btnRunByWebClient.Text = "用 WebClient 开始下载";
}
} private void Webc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null && !e.Cancelled)
{
MessageBox.Show("下载时出现错误: " + e.Error.Message);
CanChange = true;
progressBar1.Value = ;
}
else
{
DownloadNext();
}
} private void Webc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = progressBar1.Maximum - ((ToDownload.Count + ) * ) + e.ProgressPercentage;
} Queue<int> ToDownload = new Queue<int>(); private void DownloadNext()
{
if (ToDownload.Any())
{
int nextId = ToDownload.Dequeue();
TaskDemo101.RunByWebClient(webc, nextId);
WhenSingleDownloaded(nextId, true);
progressBar1.Value = progressBar1.Maximum - ((ToDownload.Count + ) * );
}
else
{
MessageBox.Show("全部下载完成");
CanChange = true;
progressBar1.Value = ;
btnRunByWebClient.Text = "用 WebClient 开始下载";
WhenAllDownloaded();
}
}
}
3. 运行截图
如图:

下载完成以后:

谢谢浏览!
一个简单的利用 WebClient 异步下载的示例(一)的更多相关文章
- 一个简单的利用 WebClient 异步下载的示例(三)
继续上一篇 一个简单的利用 WebClient 异步下载的示例(二) 后,继续优化它. 1. 直接贴代码了: DownloadEntry: public class DownloadEntry { p ...
- 一个简单的利用 WebClient 异步下载的示例(二)
继上一篇 一个简单的利用 WebClient 异步下载的示例(一) 后,我想把核心的处理提取出来,成 SkyWebClient,如下: 1. SkyWebClient 该构造函数中 downloadC ...
- 一个简单的利用 WebClient 异步下载的示例(五)(完结篇)
接着上一篇,我们继续来优化.我们的 SkyParallelWebClient 可否支持切换“同步下载模式”和“异步下载模式”呢,好处是大量的代码不用改,只需要调用 skyParallelWebClie ...
- 一个简单的利用 WebClient 异步下载的示例(四)
接上一篇,我们继续优化它. 1. DownloadEntry 类 public class DownloadEntry { public string Url { get; set; } public ...
- 一个简单的利用 HttpClient 异步下载的示例
可能你还会喜欢 一个简单的利用 WebClient 异步下载的示例 ,且代码更加新. 1. 定义自己的 HttpClient 类. using System; using System.Collec ...
- VC6下OpenGL 开发环境的构建外加一个简单的二维网络棋盘绘制示例
一.安装GLUT 工具包 GLUT 不是OpenGL 所必须的,但它会给我们的学习带来一定的方便,推荐安装. Windows 环境下的GLUT 本地下载地址:glut-install.zip(大小约为 ...
- 一个简单的AXIS远程调用Web Service示例
我们通常都将编写好的Web Service发布在Tomcat或者其他应用服务器上,然后通过浏览器调用该Web Service,返回规范的XML文件.但是如果我们不通过浏览器调用,而是通过客户端程序调用 ...
- [c#]WebClient异步下载文件并显示进度
摘要 在项目开发中经常会用到下载文件,这里使用winform实现了一个带进度条的例子. 一个例子 using System; using System.Collections.Generic; usi ...
- WebClient异步下载文件
namespace ConsoleAppSyncDownload{ class Program { static void Main(string[] args) { ...
随机推荐
- MySQL(10)---自定义函数
MySQL(10)---自定义函数 之前讲过存储过程,存储过程和自定义函数还是非常相似的,其它的可以认为和存储过程是一样的,比如含义,优点都可以按存储过程的优点来理解. 存储过程相关博客: 1.MyS ...
- php 利用curl_*测试数据并发
工作时遇到一个数据并发问题,因为上线之前没有测试数据并发,导致有时候网络比较差的时候导致数据重复插入数据库 , 所以利用curl_*函数专门写了一个测试数据并发的测试用例,如下: function t ...
- 1G内存VPS安装 mysql5.6 经常挂
背景介绍 去年3月份的时候参加了腾讯云主机活动,5年362,非常优惠.当时的想法是买来可以瞎整一波,虽然配置不高,但是搞点事情也够用. 配置如下,上海机房 1 核 1 GB 1 Mbps 系统盘:普通 ...
- docker下安装Redis
Docker介绍 1.节约时间.快速部署和启动 2.节约成本 3.标准化应用发布 4.方便做持续继承 5作为集群中的轻量主机或节点 6.方便构建基于SOA或者微服务架构的系统 Docker中文文档 h ...
- 高强度学习训练第十三天总结:使用Netty实现一个http服务器
Netty入门 Netty的重要性不言而喻.那么今天就来学习一下Netty. 整个项目基于Gradle搭建. Build如下所示: plugins { id 'java' } group 'cn.ba ...
- python 计算 对象 占用大小
# 这里主要是计算文件内容(str)的大小即: 统计空间占用情况, 并转换宜读单位 K,M def gen_atta_size(con): # 参数可以是任意数据类型 if con: size_b = ...
- JavaScript初探 三 (学习js数组)
JavaScript初探 (三) JavaScript数组 定义 创建数组 var 数组名 = [元素0,元素1,元素2,--] ; var arr = ["Huawei",&qu ...
- 在Dynamics CRM中自定义一个通用的查看编辑注释页面
关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复162或者20151016可方便获取本文,同时可以在第一时间得到我发布的最新的博文信息,follow me! 注释在CRM中的显示是比较特别, ...
- [转]国内阿里Maven仓库镜像Maven配置文件Maven仓库速度快
原文地址:http://www.cnblogs.com/ae6623/p/4416256.html 国内连接maven官方的仓库更新依赖库,网速一般很慢,收集一些国内快速的maven仓库镜像以备用. ...
- layui js 常用语句语法
烂笔头: layui组件使用 注意layui的版本. 在head里需要引入css/js文件. 出现 form.verify,form.val is not a function的错误信息时,注意版本, ...