MSMQ简单例子

默认 2009-11-11 17:00
         System.Timers.Timer timer = null;
         public Service1()
         {
             InitializeComponent();
         }
         protected override void OnStart(string[] args)
         {
             timer = new System.Timers.Timer();
             timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerEvent);
             timer.Interval = 1000 * 60 * Config.ProcessUserTypeInternal;
             timer.Enabled = true;
             timer.Start();
         }
         protected override void OnStop()
         {
             timer.Stop();
             Log.Close();
         }
         private void TimerEvent(object sender, System.Timers.ElapsedEventArgs args)
         {
             timer.Enabled = false;
             try
             {               
                  if (MessageQueue.Exists(queuename))//判断私有消息是否存在
                  { 
                     MessageQueue queue = new MessageQueue(queuename);
                     Message[] message = queue.GetAllMessages();
                     Log.WriteLine(message.Length.ToString());        
                 }
             }
             catch (Exception ex)
             {
                 Log.LogException(ex);
             }
             finally
             {
                 timer.Enabled = true;
             }
         }


发送MQ

             string queuename = ".\\private$\\SNSUserScore_TransferMq";//队列名称
             MessageQueue q;
             if (MessageQueue.Exists(queuename))
             {
                 q = new System.Messaging.MessageQueue(queuename);
             }
             else
             {
                 q = MessageQueue.Create(queuename);
             } 
             MessageInfo messageInfo = new MessageInfo();
             messageInfo.Title = title;
             messageInfo.Content = content;
             messageInfo.Time = System.DateTime.Now; 
             q.Send(messageInfo.ToString());







Leave a Reply