线程下载
m_thread = new Thread(new ThreadStart(DownLoadData));
??????????? m_thread.Start();
這兩行代碼中間加一句:m_thread.isBackground=true;
?
============================================================================
?
實現原理:采用WebClient進行批量下載任務,簡單的模擬迅雷下載效果!
廢話不多說,先看掩飾效果:
具體實現步驟如下:
1.新建項目:WinBatchDownload
2.先建一個Windows窗體:FrmBatchDownload,加載事件FrmBatchDownload_Load
3.放置一個Button按鈕:btnStartDownLoad,單機事件btnStartDownLoad_Click
4.放置一個DataGridView:dgvDownLoad.
5.具體代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; #region 命名空間using System.Threading; using System.Runtime.InteropServices; using System.Net; using System.Collections;#endregionnamespace WinBatchDownload {public partial class FrmBatchDownload : Form{#region 全局成員//存放下載列表List<SynFileInfo> m_SynFileInfoList;#endregion#region 構造函數public FrmBatchDownload(){InitializeComponent();m_SynFileInfoList = new List<SynFileInfo>();}#endregion#region 窗體加載事件private void FrmBatchDownload_Load(object sender, EventArgs e){//初始化DataGridView相關屬性 InitDataGridView(dgvDownLoad);//添加DataGridView相關列信息 AddGridViewColumns(dgvDownLoad);//新建任務 AddBatchDownload();}#endregion#region 添加GridView列/// <summary>/// 正在同步列表/// </summary>void AddGridViewColumns(DataGridView dgv){dgv.Columns.Add(new DataGridViewTextBoxColumn(){DataPropertyName = "DocID",HeaderText = "文件ID",Visible = false,Name = "DocID"});dgv.Columns.Add(new DataGridViewTextBoxColumn(){AutoSizeMode = DataGridViewAutoSizeColumnMode.None,DataPropertyName = "DocName",HeaderText = "文件名",Name = "DocName",Width = 300});dgv.Columns.Add(new DataGridViewTextBoxColumn(){DataPropertyName = "FileSize",HeaderText = "大小",Name = "FileSize",});dgv.Columns.Add(new DataGridViewTextBoxColumn(){DataPropertyName = "SynSpeed",HeaderText = "速度",Name = "SynSpeed"});dgv.Columns.Add(new DataGridViewTextBoxColumn(){DataPropertyName = "SynProgress",HeaderText = "進度",Name = "SynProgress"});dgv.Columns.Add(new DataGridViewTextBoxColumn(){DataPropertyName = "DownPath",HeaderText = "下載地址",Visible = false,Name = "DownPath"});dgv.Columns.Add(new DataGridViewTextBoxColumn(){DataPropertyName = "SavePath",HeaderText = "保存地址",Visible = false,Name = "SavePath"});dgv.Columns.Add(new DataGridViewTextBoxColumn(){DataPropertyName = "Async",HeaderText = "是否異步",Visible = false,Name = "Async"});}#endregion#region 添加下載任務并顯示到列表中void AddBatchDownload(){//清空行數據 dgvDownLoad.Rows.Clear();//添加列表(建立多個任務)List<ArrayList> arrayListList = new List<ArrayList>();arrayListList.Add(new ArrayList(){"0",//文件id"PPTV客戶端.exe",//文件名稱"21.2 MB",//文件大小"0 KB/S",//下載速度"0%",//下載進度"http://download.pplive.com/pptvsetup_3.2.1.0076.exe",//遠程服務器下載地址"D:\\PPTV客戶端.exe",//本地保存地址true//是否異步 });arrayListList.Add(new ArrayList(){"1","PPS客戶端.exe","14.3 MB","0 KB/S","0%","http://download.ppstream.com/ppstreamsetup.exe","D:\\PPS客戶端.exe",true});arrayListList.Add(new ArrayList(){"2","美圖看看客戶端.exe","4.1 MB","0 KB/S","0%","http://kankan.dl.meitu.com/V2/1029/KanKan_kk360Setup.exe","D:\\美圖看看客戶端.exe",true});foreach (ArrayList arrayList in arrayListList){int rowIndex = dgvDownLoad.Rows.Add(arrayList.ToArray());arrayList[2] = 0;arrayList.Add(dgvDownLoad.Rows[rowIndex]);//取出列表中的行信息保存列表集合(m_SynFileInfoList)中m_SynFileInfoList.Add(new SynFileInfo(arrayList.ToArray()));}}#endregion#region 開始下載按鈕單機事件private void btnStartDownLoad_Click(object sender, EventArgs e){//判斷網絡連接是否正常if (isConnected()){//設置不可用btnStartDownLoad.Enabled = false;//設置最大活動線程數以及可等待線程數ThreadPool.SetMaxThreads(3, 3);//判斷是否還存在任務if (m_SynFileInfoList.Count <= 0) AddBatchDownload();foreach (SynFileInfo m_SynFileInfo in m_SynFileInfoList){//啟動下載任務 StartDownLoad(m_SynFileInfo);}}else{MessageBox.Show("網絡異常!");}}#endregion#region 檢查網絡狀態//檢測網絡狀態[DllImport("wininet.dll")]extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);/// <summary>/// 檢測網絡狀態/// </summary>bool isConnected(){int I = 0;bool state = InternetGetConnectedState(out I, 0);return state;}#endregion#region 使用WebClient下載文件/// <summary>/// HTTP下載遠程文件并保存本地的函數/// </summary>void StartDownLoad(object o){SynFileInfo m_SynFileInfo = (SynFileInfo)o;m_SynFileInfo.LastTime = DateTime.Now;//再次new 避免WebClient不能I/O并發 WebClient client = new WebClient();if (m_SynFileInfo.Async){//異步下載client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);client.DownloadFileAsync(new Uri(m_SynFileInfo.DownPath), m_SynFileInfo.SavePath, m_SynFileInfo);}else client.DownloadFile(new Uri(m_SynFileInfo.DownPath), m_SynFileInfo.SavePath);}/// <summary>/// 下載進度條/// </summary>/// <param name="sender"></param>/// <param name="e"></param>void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e){SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState;m_SynFileInfo.SynProgress = e.ProgressPercentage + "%";double secondCount = (DateTime.Now - m_SynFileInfo.LastTime).TotalSeconds;m_SynFileInfo.SynSpeed = FileOperate.GetAutoSizeString(Convert.ToDouble(e.BytesReceived / secondCount), 2) + "/s";//更新DataGridView中相應數據顯示下載進度m_SynFileInfo.RowObject.Cells["SynProgress"].Value = m_SynFileInfo.SynProgress;//更新DataGridView中相應數據顯示下載速度(總進度的平均速度)m_SynFileInfo.RowObject.Cells["SynSpeed"].Value = m_SynFileInfo.SynSpeed;}/// <summary>/// 下載完成調用/// </summary>/// <param name="sender"></param>/// <param name="e"></param>void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e){//到此則一個文件下載完畢SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState;m_SynFileInfoList.Remove(m_SynFileInfo);if (m_SynFileInfoList.Count <= 0){//此時所有文件下載完畢btnStartDownLoad.Enabled = true;}}#endregion#region 需要下載文件實體類class SynFileInfo{public string DocID { get; set; }public string DocName { get; set; }public long FileSize { get; set; }public string SynSpeed { get; set; }public string SynProgress { get; set; }public string DownPath { get; set; }public string SavePath { get; set; }public DataGridViewRow RowObject { get; set; }public bool Async { get; set; }public DateTime LastTime { get; set; }public SynFileInfo(object[] objectArr){int i = 0;DocID = objectArr[i].ToString(); i++;DocName = objectArr[i].ToString(); i++;FileSize = Convert.ToInt64(objectArr[i]); i++;SynSpeed = objectArr[i].ToString(); i++;SynProgress = objectArr[i].ToString(); i++;DownPath = objectArr[i].ToString(); i++;SavePath = objectArr[i].ToString(); i++;Async = Convert.ToBoolean(objectArr[i]); i++;RowObject = (DataGridViewRow)objectArr[i];}}#endregion#region 初始化GridViewvoid InitDataGridView(DataGridView dgv){dgv.AutoGenerateColumns = false;//是否自動創建列dgv.AllowUserToAddRows = false;//是否允許添加行(默認:true)dgv.AllowUserToDeleteRows = false;//是否允許刪除行(默認:true)dgv.AllowUserToResizeColumns = false;//是否允許調整大小(默認:true)dgv.AllowUserToResizeRows = false;//是否允許調整行大小(默認:true)dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//列寬模式(當前填充)(默認:DataGridViewAutoSizeColumnsMode.None)dgv.BackgroundColor = System.Drawing.Color.White;//背景色(默認:ControlDark)dgv.BorderStyle = BorderStyle.Fixed3D;//邊框樣式(默認:BorderStyle.FixedSingle)dgv.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;//單元格邊框樣式(默認:DataGridViewCellBorderStyle.Single)dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;//列表頭樣式(默認:DataGridViewHeaderBorderStyle.Single)dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;//是否允許調整列大小(默認:DataGridViewColumnHeadersHeightSizeMode.EnableResizing)dgv.ColumnHeadersHeight = 30;//列表頭高度(默認:20)dgv.MultiSelect = false;//是否支持多選(默認:true)dgv.ReadOnly = true;//是否只讀(默認:false)dgv.RowHeadersVisible = false;//行頭是否顯示(默認:true)dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//選擇模式(默認:DataGridViewSelectionMode.CellSelect) }#endregion#region 文件相關操作類分/// <summary>/// 文件有關的操作類/// </summary>public class FileOperate{#region 相應單位轉換常量private const double KBCount = 1024;private const double MBCount = KBCount * 1024;private const double GBCount = MBCount * 1024;private const double TBCount = GBCount * 1024;#endregion#region 獲取適應大小/// <summary>/// 得到適應大小/// </summary>/// <param name="size">字節大小</param>/// <param name="roundCount">保留小數(位)</param>/// <returns></returns>public static string GetAutoSizeString(double size, int roundCount){if (KBCount > size) return Math.Round(size, roundCount) + "B";else if (MBCount > size) return Math.Round(size / KBCount, roundCount) + "KB";else if (GBCount > size) return Math.Round(size / MBCount, roundCount) + "MB";else if (TBCount > size) return Math.Round(size / GBCount, roundCount) + "GB";else return Math.Round(size / TBCount, roundCount) + "TB";}#endregion}#endregion} }?
總結
- 上一篇: JSFL批量导出Flash图片(Flas
- 下一篇: 网站迁服务器要重新备案,云服务器迁移需要