DotNext by .NET Foundation and Contributors

<PackageReference Include="DotNext" Version="4.1.2" />

 AsyncWriterStream<TOutput>

sealed class AsyncWriterStream<TOutput> : WriterStream<TOutput> where TOutput : ISupplier<ReadOnlyMemory<byte>, CancellationToken, ValueTask>, IFlushable
using DotNext.Buffers; using System; using System.Buffers; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace DotNext.IO { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(new byte[] { 0, 1 })] internal sealed class AsyncWriterStream<TOutput> : WriterStream<TOutput> where TOutput : ISupplier<ReadOnlyMemory<byte>, CancellationToken, ValueTask>, IFlushable { private const int DefaultTimeout = 4000; private int timeout; public override int WriteTimeout { get { return timeout; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); timeout = value; } } public override bool CanTimeout => true; internal AsyncWriterStream(TOutput output) : base(output) { timeout = 4000; } [System.Runtime.CompilerServices.NullableContext(0)] [AsyncStateMachine(typeof(AsyncWriterStream<>.<WriteAsync>d__8))] public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token) { <WriteAsync>d__8 stateMachine = default(<WriteAsync>d__8); stateMachine.<>t__builder = AsyncValueTaskMethodBuilder.Create(); stateMachine.<>4__this = this; stateMachine.buffer = buffer; stateMachine.token = token; stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start<<WriteAsync>d__8>(ref stateMachine); return stateMachine.<>t__builder.Task; } [System.Runtime.CompilerServices.NullableContext(0)] public override void Write(ReadOnlySpan<byte> buffer) { if (!buffer.IsEmpty) { using (MemoryOwner<byte> memoryOwner = new MemoryOwner<byte>(ArrayPool<byte>.Shared, buffer.Length)) { buffer.CopyTo(memoryOwner.Span); using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeout)) using (Task task = WriteAsync(memoryOwner.Memory, cancellationTokenSource.Token).AsTask()) task.Wait(cancellationTokenSource.Token); } } } } }