简体   繁体   中英

c# MSMQ between 2 local apps not receiving all messages sent

I have created my own MSMQ wrapper class like this:

public class MsgQueue
{
    private MessageQueue messageQueue;

    public delegate void ReadMessageDelegate(string message);
    public event ReadMessageDelegate NewMessageAvailable;

    public MsgQueue(string queueName)
    {
        var queuePath = @".\Private$\" + queueName;

        if (!MessageQueue.Exists(queuePath)) MessageQueue.Create(queuePath);

        messageQueue = new MessageQueue(queuePath);
        messageQueue.Label = queueName;
        messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});

        messageQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MsgReceivedHandler);
        messageQueue.BeginReceive();
    }

    private void MsgReceivedHandler(object sender, ReceiveCompletedEventArgs e)
    {
        try
        {
            MessageQueue mq = (MessageQueue)sender;
            var message = mq.EndReceive(e.AsyncResult);

            NewMessageAvailable(message.Body.ToString());

            mq.BeginReceive();
        }
        catch (MessageQueueException)
        {
            // Handle sources of MessageQueueException.
        }

        return;
    }

    public void SendMessage(string message)
    {
        messageQueue.Send(message);
    }
}

I tested it on two separate WinForms applications.

First app sends a text message when button is clicked:

private void btn_Click(object sender, EventArgs e)
{          
   var queue = new MsgQueue.MsgQueue("GBMqueue");
   queue.SendMessage("some message text");
}

Second app is listening for any incoming messages and then tries to process it:

// declaration
private MsgQueue queue;

// preparation of the queue
private void Form1_Load(object sender, EventArgs e)
{
    queue = new MsgQueue.MsgQueue("GBMqueue");
    queue.NewMessageAvailable += Queue_NewMessageAvailable;
}

// Handler for the incoming messages
private void Queue_NewMessageAvailable(string message)
{
     // Hits here very rarely!!!
}

The problem is that I can send the message from App1 several times, but the Queue_NewMessageAvailable handler catches only one random message, not the first one - just one of those which were sent.

No exception is thrown, it just does not catch the incoming messages.

What am I doing wrong here?

I think the first App should not listen for new messages. It's possible that it takes away the messages for the second App. It should only send messages.

When you split the functionality it should work.

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