private void DownloadTiles(object args) { var downloadFinished = args as ManualResetEvent; // Loop through the tiles, and filter tiles that are already on disk. var downloadTiles = new List<TileInfo>(); for (var i = 0; i < _tiles.Count(); i++) { if (!_fileCache.Exists(_tiles[i].Index)) { downloadTiles.Add(_tiles[i]); } else { // Read tiles from disk var name = _fileCache.GetFileName(_tiles[i].Index); // Determine age of tile... var fi = new FileInfo(name); if ((DateTime.Now - fi.LastWriteTime).Days <= _tileTimeOut) continue; File.Delete(name); downloadTiles.Add(_tiles[i]); } } if (downloadTiles.Count > 0) { int count = 1; int allCount = 100; while ((count - 1) * allCount < downloadTiles.Count) { try { int temp = allCount; if (count*allCount > downloadTiles.Count) temp = downloadTiles.Count - (count - 1)*allCount; var doneEvents = new MultipleThreadResetEvent(temp); ThreadPool.SetMaxThreads(25, 25); for (int i = 0; i < temp; i++) { TileInfo t = downloadTiles[(count - 1)*allCount + i]; object o = new object[] {t, doneEvents}; ThreadPool.QueueUserWorkItem(DownloadTile, o); } doneEvents.WaitAll(); doneEvents.Dispose(); //Thread.Sleep(10); count++; } catch (Exception ex) { MessageBox.Show("下载异常:" + ex.Message); } } } if (downloadFinished != null) downloadFinished.Set(); }
private void DownloadTiles() { var downloadTiles = new List<TileInfo>(); for (var i = 0; i < _tiles.Count(); i++) { if (!fileCache.Exists(_tiles[i].Index)) { downloadTiles.Add(_tiles[i]); } } if (downloadTiles.Count == 0) { MessageBox.Show("已经存在缓存文件,不需要缓存"); return; } var diare = MessageBox.Show("一共需要下载" + downloadTiles.Count + "张切片,是否继续?", "下载地图", MessageBoxButtons.OKCancel); if (diare == DialogResult.Cancel) return; progressBar1.Minimum = 0; progressBar1.Maximum = downloadTiles.Count; progressBar1.Value = 0; progressBar1.Step = 50; if (downloadTiles.Count > 0) { int count = 1; int allCount = 50; ThreadPool.SetMaxThreads(100, 100); while ((count - 1)*allCount < downloadTiles.Count) { try { int temp = allCount; if (count*allCount > downloadTiles.Count) temp = downloadTiles.Count - (count - 1)*allCount; var doneEvents = new MultipleThreadResetEvent(temp); for (int i = 0; i < temp; i++) { TileInfo t = downloadTiles[(count - 1)*allCount + i]; object o = new object[] {t, doneEvents}; ThreadPool.QueueUserWorkItem(DownloadTile, o); } int wt; int ct; ThreadPool.GetAvailableThreads(out wt, out ct); if (wt < 15) { Thread.Sleep(5000); continue; } doneEvents.WaitAll(); doneEvents.Dispose(); //Thread.Sleep(10); progressBar1.PerformStep(); label4.Text = (allCount*count).ToString() + "/" + downloadTiles.Count; Application.DoEvents(); count++; } catch (Exception ex) { MessageBox.Show("下载异常:" + ex.Message); } } MessageBox.Show("下载完毕!"); } }