public void Start(Object o) { try { // 检查是否已经停止 if (task.Status == TaskStatus.Stop) { task.TaskStop(taskId, task); task.Status = TaskStatus.Finish; return; } task.TaskStart(taskId, task); DownloadAndSave(task.Url, task.FilePath, task.FileName); Console.WriteLine(taskId + "下载完成"); task.TaskFinish(taskId, task); task.Status = TaskStatus.Finish; } catch (Exception e) { Console.WriteLine(e.Message); // 进行最多三次重试 if (retry++ < 3) { Console.WriteLine(String.Format("[{0}]下载失败,第{1}次重试中", taskId, retry)); DownloadManager.Start(this); } else { Console.WriteLine(String.Format("[{0}]下载失败已超过三次,请检查网络是否可用", taskId, retry)); task.TaskFail(taskId, task); task.Status = TaskStatus.Finish; } } }
/// <summary> /// 根据详情页url下载此页面,解析其中的图片地址并下载 /// </summary> /// <param name="pageUrl"></param> /// <param name="type"></param> private void downloadPicture(string pageUrl, string type) { // 获取缓存路径 string[] arr = pageUrl.Split('/'); string pageId = arr[arr.Length - 2]; string cacheDir = homeDir + "cache\\"; CreateDir(cacheDir); string cacheFile = cacheDir + pageId; string pictureUrl = null; // 从缓存中获取地址 if (File.Exists(cacheFile)) { pictureUrl = File.ReadAllText(cacheFile); if (pictureUrl == "") { pictureUrl = null; } } if (pictureUrl == null) { //获取详情页面信息 string html = GetHtml(pageUrl); // 检查页面是否下载成功 if (html == null || html == "") { throw new Exception("请检查网络"); } //获取图片下载地址 pictureUrl = Analyze.GetPictureUrl(html); if (pictureUrl == null) { throw new Exception("无法分析出图片地址:" + pageUrl); } // 缓存下来图片地址 CreateFile(cacheFile); File.WriteAllText(cacheFile, pictureUrl); } // 获取文件名字 string pictureName = Analyze.GetFileName(pictureUrl); // 文件完整路径 string fullFilePath = filePath + type + pictureName; // 判断文件是否已经存在 if (File.Exists(fullFilePath)) { AddItemToTextBox(String.Format("第{0}页第{1}张已存在,跳过", startPageNum, startPicNum)); startPicNum++; skipDownloadNum++; return; } // 使用多线程下载 Task task = new Task() { pageNum = startPageNum, picNum = startPicNum, Url = pictureUrl, FilePath = filePath + type, FileName = pictureName, TaskStart = new Task.TaskStartDelegate(delegate(int id, Task t) { // 下载开始 }), TaskStop = new Task.TaskStopDelegate(delegate(int id, Task t) { // AddItemToTextBox("下载被终止" + t.FileName); }), TaskFinish = new Task.TaskFinishDelegate(delegate(int id, Task t) { totalDownloadNum++; // 计算下载所用时间 DateTime now = DateTime.Now; TimeSpan time = now - startTime; AddItemToTextBox(String.Format("第{0}页第{1}张下载完成,已经过{2}秒", t.pageNum, t.picNum, time.TotalSeconds)); }), TaskFail = new Task.TaskFailDelegate(delegate(int id, Task t) { AddItemToTextBox(String.Format("第{0}页第{1}张下载失败", t.pageNum, t.picNum)); }), }; DownloadManager.Add(task); startPicNum++; }