/// <summary> /// Reads a line of characters asynchronously from the current stream and returns the data as a string. /// </summary> /// <param name="stream">The stream to perform the operation on.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task that represents the asynchronous read operation.</returns> public static async Task <string> ReadLineAsync(this ITextStream stream, CancellationToken cancellationToken) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { return(await stream.ReadLineAsync().WithCancellation(cancellationToken)); } catch (OperationCanceledException) { return(null); } }
/// <summary> /// Reads a line of characters asynchronously from the current stream and returns the data as a string. /// </summary> /// <param name="stream">The stream to perform the operation on.</param> /// <param name="timeout">The timeout to apply when reading from the stream.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task that represents the asynchronous read operation.</returns> public static async Task <string> ReadLineAsync(this ITextStream stream, TimeSpan timeout, CancellationToken cancellationToken) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } var cancellationTokenSource = new CancellationTokenSource(); cancellationToken.Register(cancellationTokenSource.Cancel); var task = stream.ReadLineAsync(); if (task == await Task.WhenAny(task, Task.Delay(timeout, cancellationTokenSource.Token))) { cancellationTokenSource.Cancel(); cancellationTokenSource.Dispose(); return(await task); } throw new TimeoutException(); }