Exemple #1
0
    public static async ValueTask <FlushResult> FlushAndCheckIsCanceledAsync(this PipeWriter writer, CancellationToken cancellationToken = default)
    {
        FlushResult flushResult = await writer.FlushAsync(cancellationToken);

        flushResult.ThrowIfCanceled(cancellationToken);
        return(flushResult);
    }
Exemple #2
0
    public static async ValueTask <long> CopyToAsync(
        this PipeReader reader,
        PipeWriter target,
        long size,
        CancellationToken cancellationToken = default)
    {
        Requires.Range(size >= 0, nameof(size), @"size must >=0.");
        long readSize = 0L;

        while (true)
        {
            ReadResult result = await reader.ReadAsync(cancellationToken);

            ReadOnlySequence <byte> buffer = result.Buffer;
            if (buffer.Length > size)
            {
                buffer = buffer.Slice(0, size);
            }
            SequencePosition position = buffer.Start;
            SequencePosition consumed = position;

            try
            {
                while (buffer.TryGet(ref position, out ReadOnlyMemory <byte> memory))
                {
                    FlushResult flushResult = await target.WriteAsync(memory, cancellationToken);

                    flushResult.ThrowIfCanceled(cancellationToken);

                    readSize += memory.Length;
                    consumed  = position;

                    if (flushResult.IsCompleted)
                    {
                        return(readSize);
                    }
                }

                consumed = buffer.End;
                size    -= buffer.Length;

                if (size <= 0 || result.IsCompleted)
                {
                    break;
                }
            }
            finally
            {
                reader.AdvanceTo(consumed);
            }
        }

        return(readSize);
    }