收听msmq队列

时间:2010-07-14 16:18:38

标签: msmq

以下是我从Windows窗体收听消息的代码。

我注意到,当我点击send时,它会向MyQueue发送一条消息,但那时我希望事件mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)应该被调用但是它不是,换句话说我正在尝试从Windows表单订阅MyQueue。只是想知道我是否遗漏了代码中的内容:

public class Form1 : System.Windows.Forms.Form
{
   public System.Messaging.MessageQueue mq;
   public static Int32 j=0;

   public Form1()
   {
       // Required for Windows Form Designer support
       InitializeComponent();

       // Queue Creation
       if(MessageQueue.Exists(@".\Private$\MyQueue"))
         mq = new System.Messaging.MessageQueue(@".\Private$\MyQueue");
       else
         mq = MessageQueue.Create(@".\Private$\MyQueue");

       mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
       mq.BeginReceive();
   }

   [STAThread]
   static void Main() 
   {
       Application.Run(new Form1());
   }

   private void btnMsg_Click(object sender, System.EventArgs e)
   {
      // SendMessage(Handle, 1, 0, IntPtr.Zero);
      System.Messaging.Message mm = new System.Messaging.Message();
      mm.Body = txtMsg.Text;
      mm.Label = "Msg" + j.ToString();
      j++;
      mq.Send(mm);
   }

   void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
   {
       //throw new NotImplementedException();
   }

   private void btnRcv_Click(object sender, System.EventArgs e)
   {
        System.Messaging.Message mes;
        string m;

        try
        {
            mes = mq.Receive(new TimeSpan(0, 0, 3));
            mes.Formatter = new XmlMessageFormatter(new String[] {"System.String,mscorlib"});
            m = mes.Body.ToString();
        }
        catch
        {
            m = "No Message";
        }
        MsgBox.Items.Add(m.ToString());
    }
}

1 个答案:

答案 0 :(得分:2)

请参阅MSDN's example on how to use the ReceiveCompletedEventHandler

他们有一个控制台应用,其中Main()Form1()的做法相同,但您的处理程序没有任何代码。你已经说它不会回调你的事件委托,但也许在构造函数上检查你的队列名是否正确。

考虑在新的控制台应用中使用MSDN的示例代码来首先测试您的环境,然后回过头来学习WinForms代码。

private static void MyReceiveCompleted(Object source, 
        ReceiveCompletedEventArgs asyncResult)
    {
        MessageQueue mq = (MessageQueue)source;
        Message m = mq.EndReceive(asyncResult.AsyncResult);

        Console.WriteLine("Message: " + (string)m.Body);
        mq.BeginReceive();      
        return; 
    }

如果您想检查队列并在点击按钮时收到消息,您只需将语句mq.BeginReceive();移至btnRcv_Click()代替.Receive();