Example #1
0
        public void Receive(Func <IReceiveContext, Action <IReceiveContext> > callback, TimeSpan timeout)
        {
            int messageCount = Count;

            bool waited = false;

            if (messageCount == 0)
            {
                if (!_messageReady.WaitOne(timeout, true))
                {
                    return;
                }

                waited = true;
            }

            bool monitorExitNeeded = true;

            if (!Monitor.TryEnter(_messageLock, timeout))
            {
                return;
            }

            try
            {
                for (LinkedListNode <LoopbackMessage> iterator = _messages.First;
                     iterator != null;
                     iterator = iterator.Next)
                {
                    if (iterator.Value != null)
                    {
                        LoopbackMessage message = iterator.Value;
                        if (message.ExpirationTime.HasValue && message.ExpirationTime <= DateTime.UtcNow)
                        {
                            _messages.Remove(iterator);
                            return;
                        }

                        ReceiveContext context = ReceiveContext.FromBodyStream(message.Body);
                        context.SetMessageId(message.MessageId);
                        context.SetContentType(message.ContentType);
                        context.SetOriginalMessageId(message.OriginalMessageId);
                        if (message.ExpirationTime.HasValue)
                        {
                            context.SetExpirationTime(message.ExpirationTime.Value);
                        }

                        Action <IReceiveContext> receive = callback(context);
                        if (receive == null)
                        {
                            continue;
                        }

                        _messages.Remove(iterator);

                        using (message)
                        {
                            Monitor.Exit(_messageLock);
                            monitorExitNeeded = false;

                            receive(context);
                            return;
                        }
                    }
                }

                if (waited)
                {
                    return;
                }

                // we read to the end and none were accepted, so we are going to wait until we get another in the queue
                _messageReady.WaitOne(timeout, true);
            }
            finally
            {
                if (monitorExitNeeded)
                {
                    Monitor.Exit(_messageLock);
                }
            }
        }