public override async Task <int> Read(long position, byte[] buffer, int offset, int count, int timeout) { if (count == 0 || item.Length == 0) { return(0); } var timeouttime = DateTime.UtcNow.AddMilliseconds(timeout); int red; using (var timeoutcancel = new CancellationTokenSource(timeout)) { if (downloader != null) { try { if (position >= item.Length) { Log.Error($"Expected length: {item.Length} Position to read: {position}"); } await downloader.WaitToPosition(position, timeoutcancel.Token); } catch (TaskCanceledException) { throw new TimeoutException($"File is too big to be downloaded in time for Read: {item.Name} Downloaded: {downloader.Downloaded} Pos: {position} Downloader completed: {downloader.Task.IsCompleted}"); } } await readStreamSync.WaitAsync(); try { stream.Position = position; if (downloader == null) { red = await stream.ReadAsync(buffer, offset, (int)Math.Min(count, item.Length - position)); } else { red = await stream.ReadAsync(buffer, offset, (int)Math.Min(count, downloader.Downloaded - position)); } } finally { readStreamSync.Release(); } if (red == 0) { throw new Exception($"Red 0 File: {filePath} Len: {item.Length} Pos: {position}"); } return(red); } }
public override async Task <int> Read(long position, byte[] buffer, int offset, int count, int timeout = 1000) { if (count == 0 || item.Length == 0) { return(0); } if (position >= item.Length) { Log.Trace($"Expected length: {item.Length} Position to read: {position}"); return(0); } using (var timeoutcancel = new CancellationTokenSource(timeout)) { try { if (downloader != null) { await downloader.WaitToPosition(position, timeoutcancel.Token); } await readStreamSync.WaitAsync(timeoutcancel.Token); int red; try { stream.Position = position; var toread = (int)Math.Min(count, (downloader?.Downloaded ?? item.Length) - position); if (toread < 0) { Log.ErrorTrace("toread less than zero:" + item.Name); } red = await stream.ReadAsync(buffer, offset, toread, timeoutcancel.Token); } finally { readStreamSync.Release(); } if (red == 0) { throw new Exception($"Red 0 File: {filePath} Len: {item.Length} Pos: {position}"); } return(red); } catch (TaskCanceledException ex) { throw new TimeoutException($"File is too big to be downloaded in time for Read: {item.Name} Downloaded: {downloader?.Downloaded.ToString() ?? "N/A"} Pos: {position} Downloader completed: {downloader?.Task.IsCompleted.ToString() ?? "N/A"}\r\n{ex}"); } } }