Pregunta

Rather than using .Purge(), is there a way to delete a defined number of messages from a queue?

I've tried setting up a MessageEnumerator and using .RemoveCurrrent after I've done whatever I need to do with the current message but it does not seem to work.

Thanks

public Message[] Get10(MessageQueue q)
    {

        int counter = 0;
        int mCount = 0;
        List<Message> ml = new List<Message>();
        try
        {
            MessageEnumerator me = q.GetMessageEnumerator2();
            while (me.MoveNext())
            {
                counter++;
            }
            if (counter > 10)
            {
                mCount = 10;
            }
            else
            {
                mCount = counter;
            }
            counter = 0;
            me.Reset();
            do
            {
                me.MoveNext();
                counter++;
                ml.Add(me.Current);
                me.RemoveCurrent();
            } while (counter < mCount);

        }

        catch (Exception x)
        {
            Console.WriteLine(x.Message);
        }
        Message[] m = ml.ToArray();
        return m;
    }
¿Fue útil?

Solución

When you call RemoveCurrent(), the enumerator is moved to the next message. You do not have to call MoveNext() after calling RemoveCurrent().

Another approach you may try is something like the following:

    List<Message> ml = new List<Message>();
    int count = 0;

    while(  count < 10 ) {
        ml.Add(me.RemoveCurrent());
        ++count;
    }

In this case, you must be aware that RemoveCurrent will wait forever if there are no messages left in the queue. If that is not what you want, you may want to use the RemoveCurrent(TimeSpan timeout) overload and catch the MessageQueueException that get thrown in case of timeout. The MessageQueueException class has a MessageQueueErrorCode property that is set to MessageQueueErrorCode.IOTimeout if a timeout has expired.

Or also (this will get at most 10 messages: the loop will exit if the message count in your queue drops to zero):

    List<Message> ml = new List<Message>();
    int count = 0;

    while( me.MoveNext() && count < 10 ) {
        ml.Add(queue.ReceiveById(me.Current.Id));
        ++count;
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top