internal async Task UpdateAsync() { App.Window.Dispatcher.Invoke(() => { MainWindow.DownloadDialog.ShowAsync(); MainWindow.DownloadDialog.DownloadUpdateAsync(this); }); OnDownloadProgressChanged?.Invoke(0); WebClient webClient = new WebClient(); webClient.DownloadProgressChanged += (sender, e) => { OnDownloadProgressChanged?.Invoke(e.ProgressPercentage); }; string tempFname = Path.GetTempFileName(); await webClient.DownloadFileTaskAsync(UpdateUrl, tempFname); OnDownloaded?.Invoke(); Thread.Sleep(3000); string oldFilename = Assembly.GetExecutingAssembly().Location; string ps = Resources.UpdateScript.Replace("##01", tempFname).Replace("##02", oldFilename); ExecuteCommand(ps); Environment.Exit(0); }
private async void DownloadFile(MyFile file) { try { using (var client = new HttpClient()) { var response = client.GetAsync(file.Url); using (var fs = new FileStream(file.PathToSave + $"{file.FileID}.jpg", FileMode.CreateNew)) { await response.Result.Content.CopyToAsync(fs); } OnDownloaded?.Invoke($"Файл {file.FileID} загружен"); } } catch (Exception e) { OnFailed?.Invoke($"Файл {file.FileID} не загружен", e); } if (downloadingQueue.TryDequeue(out file)) { DownloadFile(file); } else { CurrentThreadCount--; } }
public Task StartListenDownload() { _hasStopd = false; _stop = false; return(Task.Factory.StartNew(async() => { var rand = new Random(); while (!_stop) { if (_downloadQueue.Count == 0) { Thread.Sleep(500); } else { if (_downloadQueue.TryDequeue(out var item)) { var jsonStr = await xmlyClicnt.GetStringAsync(item.Href); var downloadUrl = GetM4a(jsonStr); var bytes = await _downloadClient.GetByteArrayAsync(downloadUrl); if (bytes == null) { _downloadQueue.Enqueue(item); Console.WriteLine($"{item.Title} 下载失败"); continue; } var file = Path.Combine (_saveDir, _saveSubDir1, item.DirName, item.Index + "-" + item.Title + ".m4a"); var dir = Path.GetDirectoryName(file); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } else if (File.Exists(file)) { continue; //File.Delete(file); } await using var fs = new System.IO.FileStream(file, System.IO.FileMode.CreateNew); fs.Write(bytes, 0, bytes.Length); //暂停 200 ~ 3200毫秒 int sleepTime = 200; // = (int)(rand.NextDouble() * 3 * 1000 + 200); OnDownloaded?.Invoke(item); Thread.Sleep(sleepTime); } } } _hasStopd = true; }, TaskCreationOptions.LongRunning)); }
private async Task CreateDownload(string url, string pathToSave, string id) { try { int fileSize = await GetFileSize(url); var finalPathToSave = pathToSave + "\\" + Path.GetFileName(url); using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage(HttpMethod.Get, url)) { using ( Stream contentStream = await(await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(), stream = new FileStream(finalPathToSave, FileMode.Create)) { var buffer = new byte[4096]; var downloaded = 0; while (true) { var length = contentStream.Read(buffer, 0, buffer.Length); if (length <= 0) { break; } await stream.WriteAsync(buffer, 0, length); downloaded += length; if (downloaded % 102400 == 0) { Task.Factory.StartNew(() => OnFileProgress?.Invoke(id, fileSize, downloaded)).Wait(); } } } } } OnDownloaded?.Invoke(id); } catch (Exception ex) { OnFailed?.Invoke(id, ex); } ManageDownloads(); }
private async Task DownloadFileAsync(FileModel file) { await Task.Run(async() => { try { using (var response = client.GetAsync(file.Url)) { using (var stream = new FileStream(file.PathToSave, FileMode.Create)) { await response.Result.Content.CopyToAsync(stream); } } OnDownloaded?.Invoke($"File {file.FileId} downloaded"); } catch (Exception e) { OnFailed?.Invoke($"Downloading of file {file.FileId} canceled", e); } }); countOfDownloadTasks--; }
private async Task Download(FSItem item, Stream result, Downloader downloader) { try { Log.Trace($"Started download: {item.Name} - {item.Id}"); var start = Stopwatch.StartNew(); var buf = new byte[64 << 10]; var uncommitedSize = 0; const int commitSize = 512 << 10; using (result) using (var writer = new BufferedStream(result)) { OnDownloadStarted?.Invoke(item); while (writer.Length < item.Length) { var stream = await cloud.Files.Download(item.Id); stream.Position = writer.Length; int red; do { red = await stream.ReadAsync(buf, 0, buf.Length); if (writer.Length == 0) { Log.Trace($"Got first part: {item.Name} - {item.Id} in {start.ElapsedMilliseconds}"); } await writer.WriteAsync(buf, 0, red); uncommitedSize += red; if (uncommitedSize <= commitSize) { continue; } uncommitedSize = 0; await writer.FlushAsync(); downloader.Downloaded = writer.Length; }while (red > 0); } await writer.FlushAsync(); downloader.Downloaded = writer.Length; } Log.Trace($"Finished download: {item.Name} - {item.Id}"); OnDownloaded?.Invoke(item); if (access.TryAdd( item.Id, new CacheEntry { Id = item.Id, AccessTime = DateTime.UtcNow, Length = item.Length })) { TotalSizeIncrease(item.Length); } if (TotalSize > CacheSize) { var task = cleanSizeWorker.Run(TotalSize - CacheSize); } if (start.ElapsedMilliseconds > 29000) { Log.Warn($"Downloading {item.Path} took: {start.ElapsedMilliseconds}"); } } catch (Exception ex) { Log.ErrorTrace($"Download failed: {item.Name} - {item.Id}\r\n{ex}"); await downloader.Failed(); OnDownloadFailed?.Invoke(item); } finally { lock (DownloadersLock) { Downloaders.Remove(item.Path); } } }
public static IEnumerator DownloadBundle(AssetBundleMeta meta, Action <AssetBundle> response = default) { State = StateDownload.None; while (!Caching.ready) { yield return(null); } hash = Hash128.Parse(meta.Name); if (DownloadResourseManager.AllAssets.ContainsKey(meta)) { State = StateDownload.Success; response?.Invoke(DownloadResourseManager.AllAssets[meta]); OnDownloaded?.Invoke(); Debug.Log($"Load from Memory <color=green>{meta.Name}</color>."); } using (uwr = UnityWebRequest.Head(meta.Url)) { async = uwr.SendWebRequest(); while (!async.isDone && string.IsNullOrEmpty(uwr.error)) { yield return(null); } State = string.IsNullOrEmpty(uwr.error) ? StateDownload.Success : StateDownload.Error; if (State == StateDownload.Error) { using (uwr = UnityWebRequestAssetBundle.GetAssetBundle(meta.Url, hash)) { async = uwr.SendWebRequest(); while (!async.isDone && string.IsNullOrEmpty(uwr.error)) { yield return(null); } State = string.IsNullOrEmpty(uwr.error) ? StateDownload.Success : StateDownload.Error; if (State == StateDownload.Error) { OnError?.Invoke(uwr); Debug.Log($"{uwr.responseCode}\n" + $"<color=red>{uwr.error}</color>"); yield break; } else { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr); if (bundle != null) { if (DownloadResourseManager.AllAssets.ContainsKey(meta)) { DownloadResourseManager.AllAssets.Remove(meta); } DownloadResourseManager.AllAssets.Add(meta, bundle); response?.Invoke(bundle); OnDownloaded?.Invoke(); Debug.Log($"Load from CACHE <color=green>{bundle.name}</color>."); } } } } else { contentLength = Convert.ToInt64(uwr.GetResponseHeader("Content-Length")); if (contentLength / Math.Pow(1024, 2) > SystemInfo.systemMemorySize) { State = StateDownload.Error; Debug.Log("<color=red>Not anough memory on device.</color>"); yield break; } } } using (uwr = UnityWebRequestAssetBundle.GetAssetBundle(meta.Url, hash)) { async = uwr.SendWebRequest(); while (!async.isDone && string.IsNullOrEmpty(uwr.error)) { yield return(null); } State = string.IsNullOrEmpty(uwr.error) ? StateDownload.Success : StateDownload.Error; if (State == StateDownload.Error) { OnError?.Invoke(uwr); Debug.Log($"{uwr.responseCode}\n" + $"<color=red>{uwr.error}</color>"); yield break; } else { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr); if (bundle != null) { if (DownloadResourseManager.AllAssets.ContainsKey(meta)) { DownloadResourseManager.AllAssets.Remove(meta); } DownloadResourseManager.AllAssets.Add(meta, bundle); response?.Invoke(bundle); OnDownloaded?.Invoke(); } } } }
public void CheckDownload(string str) { OnDownloaded?.Invoke(str); }
private async Task Download(FSItem item, Stream writer, Downloader downloader) { Log.Trace("Started download: " + item.Id); var start = Stopwatch.StartNew(); var buf = new byte[4096]; using (writer) try { OnDownloadStarted?.Invoke(item.Id); while (writer.Length < item.Length) { await amazon.Files.Download(item.Id, fileOffset : writer.Length, streammer : async(response) => { var partial = response.StatusCode == System.Net.HttpStatusCode.PartialContent; ContentRangeHeaderValue contentRange = null; if (partial) { contentRange = response.Headers.GetContentRange(); if (contentRange.From != writer.Length) { throw new InvalidOperationException("Content range does not match request"); } } using (var stream = response.GetResponseStream()) { int red = 0; do { red = await stream.ReadAsync(buf, 0, buf.Length); if (writer.Length == 0) { Log.Trace("Got first part: " + item.Id + " in " + start.ElapsedMilliseconds); } writer.Write(buf, 0, red); downloader.Downloaded = writer.Length; }while (red > 0); } }); if (writer.Length < item.Length) { await Task.Delay(500); } } Log.Trace("Finished download: " + item.Id); OnDownloaded?.Invoke(item.Id); access.TryAdd(item.Id, new CacheEntry { Id = item.Id, AccessTime = DateTime.UtcNow, Length = item.Length }); TotalSize += item.Length; if (TotalSize > CacheSize) { StartClear(TotalSize - CacheSize); } } catch (Exception ex) { OnDownloadFailed?.Invoke(item.Id); Log.Error($"Download failed: {item.Id}\r\n{ex}"); } finally { Downloader remove; downloaders.TryRemove(item.Path, out remove); } }