private void DownLoadDork(object obj) { DownLoadParams dparm = obj as DownLoadParams; foreach (var item in dparm.TrafficGroupParam) { try { Download(item); } catch (Exception ex) { string path = $"{AppDomain.CurrentDomain.BaseDirectory}/errorInfo.txt"; StreamWriter sw = new StreamWriter(path, true); sw.WriteLine(ex.ToString()); sw.Close();//写入读取的数据 } } }
/// <summary> /// 下载方法(读取传入对象) /// </summary> /// <param name="paramList"></param> /// <param name="success"></param> /// <param name="fail"></param> public void Execute(List <TrafficGroupParam> paramList) { var fileInfo = paramList.GroupBy(e => e.PlateNo).Select(e => new GroupFileInfo { FileName = e.Key, TrafficGroupParamList = e.ToList() }).ToList(); string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; if (paramList.Count < 1) { throw new Exception("没有要导出的文件!"); } foreach (var item in fileInfo) { string tempPath = string.IsNullOrEmpty(item.TrafficGroupParamList[0].SavePath) == true ? baseDirectory : item.TrafficGroupParamList[0].SavePath; tempPath = Path.Combine(tempPath, item.FileName); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } //如果小于或等于容器大小.则无需开启线程编译 DownLoadParams downloadParam = null; var pathsCount = item.TrafficGroupParamList.Count;//图片数量,用于判断是否启用多线程 if (pathsCount <= Number100) { downloadParam = new DownLoadParams() { TrafficGroupParam = item.TrafficGroupParamList.ToArray() }; DownLoadDork(downloadParam); } else { // 计算编译线程数量 int threadCount = pathsCount % Number100 == 0 ? pathsCount / Number100 : pathsCount / Number100 + 1; if (threadCount > MaxThreadCount) { threadCount = MaxThreadCount; } int threadPqgeSize = (pathsCount / threadCount) + 1; int typeSum = 0; // 为每个线程准备调用参数 List <DownLoadParams> parameters = new List <DownLoadParams>(threadCount); TrafficGroupParam[] trafficGroupParam = null; int index, endSize = 0;; for (int i = 0; i < threadCount; i++) { downloadParam = new DownLoadParams(); endSize = threadPqgeSize * (i + 1); if (endSize > pathsCount) { trafficGroupParam = new TrafficGroupParam[threadPqgeSize + pathsCount - endSize]; endSize = pathsCount; } else { trafficGroupParam = new TrafficGroupParam[threadPqgeSize]; } index = 0; for (int j = typeSum; j < endSize; j++) { trafficGroupParam[index++] = item.TrafficGroupParamList[j]; } downloadParam.TrafficGroupParam = trafficGroupParam; parameters.Add(downloadParam); } // 创建编译线程 List <Thread> threads = new List <Thread>(threadCount); for (int i = 1; i < threadCount; i++) { Thread thread = new Thread(DownLoadDork); thread.IsBackground = true; thread.Name = "DownloadThread #" + i.ToString(); threads.Add(thread); thread.Start(parameters[i]); } // 重用当前线程:为当前线程指派下载任务。 DownLoadDork(parameters[0]); // 等待所有的下载线程执行线束。 foreach (Thread thread in threads) { thread.Join(); } } } //success = tempSuccess; //fail = tempFail; }