//public delegate void onDownloadingUpdate(string shortCode, int ep, float progress); //public static event onDownloadingUpdate OnDownloadUpdateEvent; static FileDownloader() { _queue = new Queue <FileDownloadInfo>(); _downloadingFile = null; _webClient = new HttpClient(); //Shouldnt cause any problems for downloading but may make someone watching agents server side double check :) _webClient.DefaultRequestHeaders.Add("User-Agent", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"); _downloadingStream = null; _runThread = true; _doThread = new Thread(RunThread); _doThread.Name = "FileDownloader"; _doThread.Start(); }
private static void RunThread() { do { Thread.Sleep(500); if (_queue.Count > 0 && _downloadingFile == null) { _downloadingFile = _queue.Dequeue(); if (_downloadingFile != null) { try { var path = Path.GetDirectoryName(_downloadingFile.FilePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } RunFileRequest().ConfigureAwait(false); } catch (Exception ex) { OnDownloadFinishedEvent?.Invoke(false, _downloadingFile.EpNumber, _downloadingFile.PodcastShortCode); ErrorTracker.CurrentError = ex.Message; } } } else if (_downloadingFile != null && _downloadingStream != null) { try { //OnDownloadUpdateEvent?.Invoke(_downloadingFile.PodcastShortCode, _downloadingFile.EpNumber, _downloadingStream.Length / _downloadingStream.Position); } catch { } } }while (_runThread); return; }
private static async Task RunFileRequest() { try { await Task.Run(() => ProcessFileRequest()).TimeoutAfter(45000); if (File.Exists(_downloadingFile.FilePath)) { OnDownloadFinishedEvent?.Invoke(true, _downloadingFile.EpNumber, _downloadingFile.PodcastShortCode); } else { OnDownloadFinishedEvent?.Invoke(false, _downloadingFile.EpNumber, _downloadingFile.PodcastShortCode); } } catch (Exception ex) { cancelSource.Cancel(); OnDownloadFinishedEvent?.Invoke(false, _downloadingFile.EpNumber, _downloadingFile.PodcastShortCode); ErrorTracker.CurrentError = ex.Message; } finally { //These should already be disposed. if (_fileStream != null) { _fileStream = null; } if (_downloadingStream != null) { _downloadingStream = null; } cancelSource.Dispose(); cancelSource = new CancellationTokenSource(); _downloadingFile = null; } }
public static void AddFile(FileDownloadInfo info) { _queue.Enqueue(info); }