private async Task <IEventStream> SubscribeInternalAsync(
            IEventDescription eventDescription)
        {
            await _semaphore.WaitAsync().ConfigureAwait(false);

            try
            {
                if (!_streams.TryGetValue(eventDescription,
                                          out List <InMemoryEventStream> subscribers))
                {
                    subscribers = new List <InMemoryEventStream>();
                    _streams[eventDescription] = subscribers;
                }

                var eventMessage = new EventMessage(eventDescription);
                var stream       = new InMemoryEventStream();
                stream.Completed += (s, e) => Unsubscribe(eventMessage, stream);
                subscribers.Add(stream);
                return(stream);
            }
            finally
            {
                _semaphore.Release();
            }
        }
Exemplo n.º 2
0
        public async Task <IEventStream> SubscribeAsync(
            IEventDescription eventReference)
        {
            if (eventReference == null)
            {
                throw new ArgumentNullException(nameof(eventReference));
            }

            await _semaphore.WaitAsync();

            try
            {
                if (!_streams.TryGetValue(eventReference, out var subscribers))
                {
                    subscribers = new List <InMemoryEventStream>();
                    _streams[eventReference] = subscribers;
                }

                var eventMessage = new EventMessage(eventReference);
                var stream       = new InMemoryEventStream(eventMessage);
                stream.Completed += (s, e) => Unsubscribe(eventMessage, stream);
                subscribers.Add(stream);
                return(stream);
            }
            finally
            {
                _semaphore.Release();
            }
        }
        private void Unsubscribe(
            IEventMessage message,
            InMemoryEventStream stream)
        {
            _semaphore.Wait();

            try
            {
                if (_streams.TryGetValue(message.Event, out List <InMemoryEventStream> subscribers))
                {
                    subscribers.Remove(stream);
                }
            }
            finally
            {
                _semaphore.Release();
            }
        }