Exemplo n.º 1
0
    private async Task ProcessMessagesAsync(CancellationToken cancellationToken)
    {
        try
        {
            while (true)
            {
                SequencePosition?position;
                ReadResult       result = await _reader.ReadAsync(cancellationToken);

                ReadOnlySequence <byte> buffer = result.Buffer;

                do
                {
                    position = buffer.PositionOf(SubscriptionSession.Delimiter);

                    if (position is not null)
                    {
                        await _pipeline.ProcessAsync(
                            _connection,
                            buffer.Slice(0, position.Value),
                            cancellationToken);

                        // Skip the message which was read.
                        buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
                    }
                }while (position != null);

                _reader.AdvanceTo(buffer.Start, buffer.End);

                if (result.IsCompleted)
                {
                    break;
                }
            }
        }
        catch (OperationCanceledException) when(cancellationToken.IsCancellationRequested)
        {
        }
        catch (WebSocketException)
        {
            // we will just stop receiving
        }
        finally
        {
            // reader should be completed always, so that related pipe writer can
            // stop write new messages
            await _reader.CompleteAsync();
        }
    }
Exemplo n.º 2
0
        private async Task ProcessMessagesAsync(
            CancellationToken cancellationToken)
        {
            while (true)
            {
                ReadResult result = await _reader
                                    .ReadAsync(cancellationToken)
                                    .ConfigureAwait(false);

                ReadOnlySequence <byte> buffer   = result.Buffer;
                SequencePosition?       position = null;

                do
                {
                    position = buffer.PositionOf(Subscription._delimiter);

                    if (position != null)
                    {
                        await _pipeline.ProcessAsync(
                            _connection,
                            buffer.Slice(0, position.Value),
                            cancellationToken)
                        .ConfigureAwait(false);

                        // Skip the message which was read.
                        buffer = buffer
                                 .Slice(buffer.GetPosition(1, position.Value));
                    }
                }while (position != null);

                _reader.AdvanceTo(buffer.Start, buffer.End);

                if (result.IsCompleted)
                {
                    break;
                }
            }

            _reader.Complete();
        }