private Downloader StartDownload(FSItem item, string path) { var downloader = new Downloader(item, path); lock (DownloadersLock) { if (Downloaders.TryGetValue(item.Path, out Downloader result)) { if (result.Task == null) { throw new Exception("Downloader Task is Null"); } return(result); } Directory.CreateDirectory(cachePath); var fileinfo = new FileInfo(path); if (fileinfo.Exists && fileinfo.Length == item.Length) { return(Downloader.CreateCompleted(item, path, item.Length)); } Stream writer; if (!fileinfo.Exists || fileinfo.Length < item.Length) { writer = new FileStream( path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); if (writer.Length > 0) { Log.Warn( $"File was not totally downloaded before. Should be {item.Length} but was {writer.Length}: {item.Path} - {item.Id}"); downloader.Downloaded = writer.Length; } } else { writer = new FileStream( path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); } downloader.Task = Task.Factory.StartNew(async() => await Download(item, writer, downloader), TaskCreationOptions.LongRunning); Downloaders.Add(item.Path, downloader); return(downloader); } }
private Downloader StartDownload(FSItem item, string path) { if (item.Length == 0) { Log.Error($"Downloader expected length Zero: {item.Name} - {item.Id}"); } var downloader = new Downloader(item, path); Stream writer; lock (downloadersLock) { Downloader result; if (downloaders.TryGetValue(item.Path, out result)) { if (result.Task == null) { throw new Exception("Downloader Task is Null"); } return(result); } Directory.CreateDirectory(cachePath); writer = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); if (writer.Length == item.Length) { writer.Close(); return(Downloader.CreateCompleted(item, path, item.Length)); } if (writer.Length > 0) { Log.Warn($"File was not totally downloaded before. Should be {item.Length} but was {writer.Length}: {path}"); downloader.Downloaded = writer.Length; } downloader.Task = Task.Factory.StartNew(async() => await Download(item, writer, downloader), TaskCreationOptions.LongRunning); downloaders.Add(item.Path, downloader); return(downloader); } }