在这资源更新的进度条显示时
代码语言:javascript复制 using (WebClient client = new WebClient()) {
sw.Start();
client.DownloadProgressChanged = new DownloadProgressChangedEventHandler(ProgressChanged);
client.DownloadFileAsync(new System.Uri(url), currDownFile);
}
注册上进度条下载的委托和下载完成的委托就可以了
在更新进度条的委托中可以得到下载的进度条和下载的总大小以及已经下载的大小。
用e.UserState可以取到传入的参数,由于是下载文件有可能下载多个但是更新进度条的方法都走的一个方法所以需要用UserState来取得对应下载任务的进度条。
下面贴一下这两个委托的实现方法,我将WebClient简单封装了一下。
代码语言:javascript复制private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
//下载的总量
PrecentData preData = new PrecentData();
preData.total = string.Format("{0} MB / {1} MB", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
preData.precent = (float)e.BytesReceived / (float)e.TotalBytesToReceive;
string value = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
preData.speed = value;
Loom.QueueOnMainThread((param) =>
{
NotificationCenter.Get().ObjDispatchEvent(KEventKey.m_evDownload, preData);
}, null);
NotiData data = new NotiData(NotiConst.UPDATE_PROGRESS, value);
if (m_SyncEvent != null) m_SyncEvent(data);
if (e.ProgressPercentage == 100 && e.BytesReceived == e.TotalBytesToReceive) {
sw.Reset();
data = new NotiData(NotiConst.UPDATE_DOWNLOAD, currDownFile);
if (m_SyncEvent != null) m_SyncEvent(data);
}
}
要显示下载百分比使用
代码语言:javascript复制string.Format("{0} MB / {1} MB", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
要显示当前的下载速度
代码语言:javascript复制string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));