private async Task <bool> WrappedReadOperation(ReadContext ctx, CancellationToken cancellation) { var before = ctx.Read; var r = await WrappedOperation(async() => ctx.Read += await _stream.ReadAsync(ctx.Array, ctx.Offset + ctx.Read, ctx.Len - ctx.Read, cancellation).ConfigureAwait(false), ctx.Remote).ConfigureAwait(false); ctx.Exception = r.exception; if (!r.result) { return(false); } if (ctx.Read - before < 1) { Log.Debug($"0 bytes read from {ctx.Remote}. Closing stream"); return(false); } return(true); }
private async Task <bool> ReadBytes(byte[] buffer, int offset, int count) { EndPoint remote; try { remote = _socket.RemoteEndPoint; } catch (ObjectDisposedException) { return(false); } var ctx = new ReadContext() { Array = buffer, Offset = offset, Read = 0, Len = count, Remote = remote }; var cancelation = new CancellationTokenSource(); while (!_resetEvent.WaitOne(1000)) { if (cancelation.IsCancellationRequested) { return(false); } } try { do { cancelation.CancelAfter(InactivityTimeout); if (cancelation.IsCancellationRequested) { continue; } var r = await WrappedReadOperation(ctx, cancelation.Token).ConfigureAwait(false); if (cancelation.IsCancellationRequested) { Log.Info($"{remote} is inactive for {InactivityTimeout} secs. Connection closed."); return(false); } if (!r) { return(false); } if (ctx.Exception != null) { throw ctx.Exception; } if (ctx.Read == ctx.Len) { return(true); } if (!_stream.CanRead || !_socket.Connected) { return(false); } } while (ctx.Read != ctx.Len); } finally { _resetEvent.Set(); } return(true); }