with MessageEnumerator RemoveCurrent how do I know if I am at end of queue?

余生长醉 提交于 2020-01-24 04:25:28

问题


In MSMQ on .NET, I'm using a MessageEnumerator to look through all the messages in the queue. I want to remove messages that meet a certain condition.

When I call MoveNext to step through the queue, I get back a boolean to tell me if the current message exists. But, when I do a RemoveCurrent, how do I know if the current message after the removal exists? Is the only way to check Current and handle the exception?

Here is an example where I use the simple condition of removing messages that are over one year old. Assume the queue was created elsewhere and set with MessageReadPropertyFilter.ArrivedTime = true:

private void RemoveOldMessages(MessageQueue q)
{
    MessageEnumerator me = q.GetMessageEnumerator2();
    bool hasMessage = me.MoveNext();
    while (hasMessage)
    {
        if (me.Current.ArrivedTime < DateTime.Now.AddYears(-1))
        {
            Message m = me.RemoveCurrent(new TimeSpan(1));
            // Removes and returns the current message
            // then moves to the cursor to the next message
            // How do I know if there is another message? Is this right?:
            try
            {
                m = me.Current;
                hasMessage = true;
            }
            catch (MessageQueueException ex)
            {
                hasMessage = false;
            }

        }
        else
        {
            hasMessage = me.MoveNext();
            // MoveNext returns a boolean to let me know if is another message
        }
    }
}

回答1:


Albeit belated:

Every call to RemoveCurrent() will invalidate your Enumerator. As such you need to call Reset() to keep starting at the beginning of the Enumerator (Message Queue).

private void RemoveOldMessages(MessageQueue q)
{
    MessageEnumerator me = q.GetMessageEnumerator2();

    while (me.MoveNext())
    {
        try
        {
            Message m = me.RemoveCurrent();

            // Handle Message
        }
        finally
        {
            me.Reset();
        }
    }
}


来源:https://stackoverflow.com/questions/21864043/with-messageenumerator-removecurrent-how-do-i-know-if-i-am-at-end-of-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!