简体   繁体   中英

Is it possible to prevent auto delete message after read in Msmq

IDE: VS 2010, Winforms:

I am having a simple msmq send/receive application, I have a requirement in which I will read the message and based on message I will call other function if that function is not ready then I want message to be in queue.

My Msmq Send receive code:

private void button1_Click(object sender, EventArgs e)
    {
        //MSMQ Send :
        if (MessageQueue.Exists(@".\Private$\MyQ"))
        {
            myQ = new MessageQueue(@".\Private$\MyQ");
        }
        else
        {
            myQ = MessageQueue.Create(@".\Private$\MyQ");
        }

        string xmlText = getxmlString();

        System.Messaging.Message msg = new System.Messaging.Message();

        msg.Formatter = new XmlMessageFormatter();
        msg.Body = xmlText;
        msg.Label = "MyXmlMessage";
        msg.Priority = MessagePriority.Normal;
        myQ.Send(msg);

    }  


 private void button2_Click(object sender, EventArgs e)
    {
        //MSMQ Receive
        myQ = new MessageQueue(@".\Private$\MyQ");

        System.Messaging.Message myMsg = myQ.Receive();
        myMsg.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
        bool IsValidated  = Validate(myMsg.Body.ToString());
    }  

    internal void Validate(string message)
    {
        //some logic  
        return false;
    }  

As you can see in receive code, I am receiving the message back and validating the message, Here I want that message to be deleted from queue only if the IsValidated is true,

Basically I want to prevent the auto delete message future to false and want to delete that message in queue if it is validated.

can you tell me what modification shall i make to achieve this goal.

Have you tried Peek ?

MessageQueue.Peek Method

Returns without removing (peeks) the first message in the queue referenced by this MessageQueue. The Peek method is synchronous, so it blocks the current thread until a message becomes available.

messageQueue.Formatter = new XmlMessageFormatter(
  new Type[] { typeof(System.Xml.XmlElement) });
MessageEnumerator iter = messageQueue.GetMessageEnumerator2();
iter.Reset();
while (iter.MoveNext(new TimeSpan(1000)))
{
    System.Messaging.Message msg = iter.Current;

    msg.Formatter = new ActiveXMessageFormatter();
    var reader = new StreamReader(msg.BodyStream);

    var msgBody = reader.ReadToEnd();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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