简体   繁体   English

从消息队列中删除定义数量的消息

[英]remove a defined number of messages from a message queue

Rather than using .Purge() , is there a way to delete a defined number of messages from a queue? 除了使用.Purge() ,还有没有办法从队列中删除定义数量的消息?

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. 在完成对当前消息的所有.RemoveCurrrent后,我尝试设置MessageEnumerator并使用.RemoveCurrrent ,但它似乎不起作用。

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;
    }

When you call RemoveCurrent() , the enumerator is moved to the next message. 当您调用RemoveCurrent() ,枚举器将移至下一条消息。 You do not have to call MoveNext() after calling RemoveCurrent() . 你不必调用MoveNext()调用后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. 在这种情况下,您必须知道,如果队列中没有剩余消息,则RemoveCurrent将永远等待。 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. 如果这不是您想要的,则可能需要使用RemoveCurrent(TimeSpan timeout)重载并捕获在超时情况下抛出的MessageQueueException The MessageQueueException class has a MessageQueueErrorCode property that is set to MessageQueueErrorCode.IOTimeout if a timeout has expired. 如果超时已过期,则MessageQueueException类具有一个MessageQueueErrorCode属性,该属性设置为MessageQueueErrorCode.IOTimeout

Or also (this will get at most 10 messages: the loop will exit if the message count in your queue drops to zero): 也可以( 最多获取10条消息:如果队列中的消息计数降至零,则循环将退出):

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

    while( me.MoveNext() && count < 10 ) {
        ml.Add(queue.ReceiveById(me.Current.Id));
        ++count;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM