Ejemplo n.º 1
0
        private static bool PushIfCompatibleType(
            ILazyMessageStreamEnumerable lazyStream,
            int messageId,
            TMessage message,
            CancellationToken cancellationToken,
            out Task messageProcessingTask)
        {
            if (message == null)
            {
                messageProcessingTask = Task.CompletedTask;
                return(false);
            }

            if (lazyStream.MessageType.IsInstanceOfType(message))
            {
                var pushedMessage = new PushedMessage(messageId, message, message);
                messageProcessingTask = lazyStream.GetOrCreateStream().PushAsync(pushedMessage, cancellationToken);
                return(true);
            }

            var envelope = message as IEnvelope;

            if (envelope?.Message != null && envelope.AutoUnwrap &&
                lazyStream.MessageType.IsInstanceOfType(envelope.Message))
            {
                var pushedMessage = new PushedMessage(messageId, envelope.Message, message);
                messageProcessingTask = lazyStream.GetOrCreateStream().PushAsync(pushedMessage, cancellationToken);
                return(true);
            }

            messageProcessingTask = Task.CompletedTask;
            return(false);
        }
        public async Task PushAsync(PushedMessage pushedMessage, CancellationToken cancellationToken = default)
        {
            Check.NotNull(pushedMessage, nameof(pushedMessage));

            using var linkedTokenSource = LinkWithAbortCancellationTokenSource(cancellationToken);

            await _writeSemaphore.WaitAsync(linkedTokenSource.Token).ConfigureAwait(false);

            if (_isComplete)
            {
                throw new InvalidOperationException($"The stream has been marked as complete.");
            }

            _current = pushedMessage;
            SafelyRelease(_readSemaphore);

            await _processedSemaphore.WaitAsync(linkedTokenSource.Token).ConfigureAwait(false);

            _writeSemaphore.Release();
        }