一个简单的利用 WebClient 异步下载的示例(二)
继上一篇 一个简单的利用 WebClient 异步下载的示例(一) 后,我想把核心的处理提取出来,成 SkyWebClient,如下:
1. SkyWebClient
该构造函数中 downloadConfigs 参数是必须的,不能为 NULL,而 ProgressBar progressBar 可为空,只不过不能显示进度条而已。
public class DownloadEntry
{
public string Url { get; set; } public string Path { get; set; } /// <summary>
/// 当前处理的数据
/// </summary>
public object Data { get; set; } public DownloadEntry(string url, string savedPath)
:this(url,savedPath, null)
{ } public DownloadEntry(string url, string savedPath, object data)
{
Url = url;
Path = savedPath;
Data = data;
}
} /// <summary>
/// 当单个下载前的事件处理
/// </summary>
/// <param name="current">当前处理的数据,有可能为 NULL,请注意判断</param>
public delegate void WhenSingleDownloadingEventHandler(DownloadEntry current); /// <summary>
/// 当全部下载完毕后的事件处理
/// </summary>
public delegate void WhenAllDownloadedEventHandler(); /// <summary>
/// 当下载错误时
/// </summary>
/// <param name="ex"></param>
public delegate void WhenDownloadingErrorEventHandler(Exception ex); public class SkyWebClient : INotifyPropertyChanged
{
#region 字段、属性 public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
} /// <summary>
/// 当单个下载前的事件处理
/// </summary>
public event WhenSingleDownloadingEventHandler WhenSingleDownloading;
private void OnWhenSingleDownloading(DownloadEntry next)
{
if (WhenSingleDownloading != null)
{
WhenSingleDownloading(next);
}
} /// <summary>
/// 当全部下载完毕后的事件处理
/// </summary>
public event WhenAllDownloadedEventHandler WhenAllDownloaded;
private void OnWhenAllDownloaded()
{
if (WhenAllDownloaded != null)
{
WhenAllDownloaded();
}
} /// <summary>
/// 当全部下载完毕后的事件处理
/// </summary>
public event WhenDownloadingErrorEventHandler WhenDownloadingError;
private void OnWhenDownloadingError(Exception ex)
{
if (WhenDownloadingError != null)
{
WhenDownloadingError(ex);
}
} ProgressBar progressBar;
WebClient webc;
Queue<DownloadEntry> ToDownload = new Queue<DownloadEntry>(); bool _canChange = true;
public bool CanChange
{
get
{
return _canChange;
}
set
{
_canChange = value;
OnPropertyChanged("CanChange");
}
} #endregion public SkyWebClient(IEnumerable<DownloadEntry> downloadConfigs)
:this(downloadConfigs, null)
{ } public SkyWebClient(IEnumerable<DownloadEntry> downloadConfigs, ProgressBar progressBar)
{
if (downloadConfigs == null)
{
throw new ArgumentNullException("downloadConfigs");
}
foreach (DownloadEntry item in downloadConfigs)
{
ToDownload.Enqueue(item);
}
this.webc = new WebClient();
this.progressBar = progressBar; webc.DownloadFileCompleted += Webc_DownloadFileCompleted; //注册下载完成事件
webc.DownloadProgressChanged += Webc_DownloadProgressChanged; //注册下载进度改变事件
} public void Start()
{
if (ToDownload.Count == )
{
Downloaded();
return;
}
if (CanChange)
{
CanChange = false;
if (this.progressBar != null)
{
this.progressBar.Maximum = ToDownload.Count * ;
}
StartCore();
}
else
{
ToDownload.Clear();
webc.CancelAsync();
CanChange = true;
//this.progressBar.Value = 0;
//btnRunByWebClient.Text = "用 WebClient 开始下载";
}
} private void StartCore()
{
DownloadEntry next = ToDownload.Dequeue();
webc.DownloadFileAsync(new Uri(next.Url), next.Path);
OnWhenSingleDownloading(next);
} private void DownloadNext()
{
if (ToDownload.Any())
{
StartCore();
if (this.progressBar != null)
{
this.progressBar.Value = this.progressBar.Maximum - ((ToDownload.Count + ) * );
}
}
else
{
if (this.progressBar != null)
{
this.progressBar.Value = ;
}
Downloaded();
}
} private void Downloaded()
{
CanChange = true;
OnWhenAllDownloaded();
} private void Webc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null && !e.Cancelled)
{
OnWhenDownloadingError(e.Error);
CanChange = true;
//this.progressBar.Value = 0;
}
else
{
DownloadNext();
}
} private void Webc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
if (this.progressBar != null)
{
this.progressBar.Value = this.progressBar.Maximum - ((ToDownload.Count + ) * ) + e.ProgressPercentage;
}
}
}
2. Form1.cs
在点击事件中,调用 SkyWebClient。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} 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)
{
WhenAllDownloading();
var ids = GetDownloadIds();
List<DownloadEntry> downloadConfigs = new List<DownloadEntry>();
Random rd = new Random();
foreach (var id in ids)
{
downloadConfigs.Add(new DownloadEntry(TaskDemo101.GetRandomUrl(rd), TaskDemo101.GetSavedFileFullName(), id));
}
SkyWebClient skyWebClient = new SkyWebClient(downloadConfigs, this.progressBar1);
skyWebClient.WhenAllDownloaded += SkyWebClient_WhenAllDownloaded;
skyWebClient.WhenSingleDownloading += SkyWebClient_WhenSingleDownloading;
skyWebClient.WhenDownloadingError += SkyWebClient_WhenDownloadingError;
skyWebClient.Start();
} private void SkyWebClient_WhenDownloadingError(Exception ex)
{
MessageBox.Show("下载时出现错误: " + ex.Message);
} private void SkyWebClient_WhenSingleDownloading(DownloadEntry current)
{
WhenSingleDownloaded((int)current.Data, true);
} private void SkyWebClient_WhenAllDownloaded()
{
btnRunByWebClient.Text = "用 WebClient 开始下载";
WhenAllDownloaded();
} }
3. 运行截图
如图:

4. 总结
由于本下载采用依次来异步下载,虽然可以保证下载的文件的完整,但单位时间内效率不高,可能进度缓慢。且如果其中一个占用了较多的时间(比如:2分钟),那么整体的下载进度就会变慢。接下来,我会逐步优化它,敬请关注!
谢谢浏览!
一个简单的利用 WebClient 异步下载的示例(二)的更多相关文章
- 一个简单的利用 WebClient 异步下载的示例(三)
继续上一篇 一个简单的利用 WebClient 异步下载的示例(二) 后,继续优化它. 1. 直接贴代码了: DownloadEntry: public class DownloadEntry { p ...
- 一个简单的利用 WebClient 异步下载的示例(一)
继上一篇文章 一个简单的利用 HttpClient 异步下载的示例 ,我们知道不管是 HttpClient,还算 WebClient,都不建议每次调用都 new HttpClient,或 new We ...
- 一个简单的利用 WebClient 异步下载的示例(五)(完结篇)
接着上一篇,我们继续来优化.我们的 SkyParallelWebClient 可否支持切换“同步下载模式”和“异步下载模式”呢,好处是大量的代码不用改,只需要调用 skyParallelWebClie ...
- 一个简单的利用 WebClient 异步下载的示例(四)
接上一篇,我们继续优化它. 1. DownloadEntry 类 public class DownloadEntry { public string Url { get; set; } public ...
- 一个简单的利用 HttpClient 异步下载的示例
可能你还会喜欢 一个简单的利用 WebClient 异步下载的示例 ,且代码更加新. 1. 定义自己的 HttpClient 类. using System; using System.Collec ...
- [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(二)
一步步打造一个简单的 MVC 电商网站 - BooksStore(二) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore 前: ...
- 一个简单的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) { ...
随机推荐
- 列举常见国内外做服务器与存储的IT厂家
列举常见国内外做服务器与存储的IT厂家 联想.浪潮.曙光.同有飞骥.迪菲特.宝德.星盈.元谷.威联通.群晖.忆捷.天敏等 华为.华三.戴尔.神州云科.同有.谷数,都是比较大的厂商 HDS(昆仑联通). ...
- 打开excel打印时报“不能使用对象链接和嵌入”
解决思路: 1.以WIN + R 打开命令行, 在命令行中输入dcomcnfg,打开组件服务. 2.在组件服务窗口中,点击到[控制根节点]->[组件服务]->[计算机]->[我的电脑 ...
- CAD如何能画的快?老师傅教你5个技巧,远超他人
都知道CAD用途是很广泛,各行各业都是离不开CAD画图设计,机械,建筑,园林,服装,家具…… 画图速度一定要够快速,这样才能够满足需求,事实上会发现有的人绘图非常快速,但是你出一张图却要加班赶点.差距 ...
- 常见的Web源码泄露总结
常见的Web源码泄露总结 源码泄露方式分类 .hg源码泄露 漏洞成因: hg init 的时候会生成 .hg 漏洞利用: 工具: dvcs-ripper .git源码泄露 漏洞成因: 在运行git i ...
- 从0系统学Android-1.4日志工具的使用
更多精品文章分类 1.4 日志工具 简单介绍一下日志工具,对以后的开发非常有用 1.4.1 使用日志工具 Log Log 日志工具类提供了 5 个方法来供我们打印信息(级别逐渐提高) Log.v(): ...
- 源码包安装转换rpm包
目录 纯净版虚拟机 1. 先安装个虚拟机,登陆nginx官网 http://nginx.org/选择一个稳定的版本 2. 右键复制地址,到新克隆的纯净虚拟机wget 下载 3.源码包 4.解压 tar ...
- 必学PHP类库/常用PHP类库大全,php 类库分类-收集
依赖管理( Dependency Management ) 用于依赖管理的包和框架 Composer / Packagist - 一个包和依赖管理器. Composer Installers - 一个 ...
- Python—版本和环境的管理工具(Pipenv)
pipenv简介 虚拟环境本质是一个文件,是为了适应不同的项目而存在.pipenv相当于virtualenv和pip的合体. 整合了 pip+virtualenv+Pipfile,能够自动处理好包的依 ...
- emacs speedbar功能介绍
emacs speedbar功能介绍 speedbar启动命令M-x speedbar,效果如下: speedbar是一个frame,它会遮挡你工作中的buffer.鼠标左键点击,或者敲回车,都会自动 ...
- postman---post请求数据类型
我们都知道接口post方法中有不同的请求类型,再写postman中发送请求的时候只是简单的写了一种,今天我们重新了解下Postman如何发送post的其他数据类型 Postman中post的数据类型 ...