.Net下的MSMQ(微软消息队列)的同步异步调用

一、MSMQ简介

 MSMQ(微软消息队列)是Windows操作系统中消息应用程序的基础,是用于创建分布式、松散连接的消息通讯应用程序的开发工具。消息队列

和电子邮件有着很多相似处,他们都包含多个属性,用于保存消息,消息类型中都指出发送者和接收者的地址;然而他们的用处却有着很大的

区别:消息队列的发送者和接收者是应用程序,而电子邮件的发送者和接收者通常是人。如同电子邮件一样,消息队列的发送和接收也不需要

发送者和接收者同时在场,可以存储在消息队列或是邮件服务器中。

 

二、消息队列的安装

 默认情况下安装操作系统是不安装消息队列的,你可以在控制面板中找到添加/删除程序,然后选择添加/删除Windows组件一项,然后选择应

用程序服务器,双击它进入详细资料中选择消息队列一项进行安装,如图:

mq1.JPG

mq2.JPG


mq3.JPG
三、消息队列类型

消息对列分为3类:
 
公共队列
 MachineName\QueueName
 能被别的机器所访问,如果你的多个项目中用到消息队列,那么你可以把队列定义为公共队列
 
专用队列
 MachineName\Private$\QueueName
 只针对于本机的程序才可以调用的队列,有些情况下为了安全起见定义为私有队列。
日志队列
 MachineName\QueueName\Journal$
 

四、消息队列的创建

MessageQueue Mq=new MessageQueue(“.\\private$\\Mymq”);

通过Path属性引用消息队列的代码也十分简单:

MessageQueue Mq=new MessageQueue();

Mq.Path=”.\\private$\\Mymq”;

使用 Create 方法可以在计算机上创建队列:

System.Messaging.MessageQueue.Create(@".\private$\Mymq");

这里注意由于在C#中要记住用反斜杠将“\”转义。

由于消息对列所放置的地方经常改变,所以建议消息队列路径不要写死,建议放在配置文件中。

五、消息的发送

消息的发送可以分为简单消息和复杂消息,简单消息类型就是常用的数据类型,例如整型、字符串等数据;复杂消息的数据类型通常对应于系

统中的复杂数据类型,例如结构,对象等等。

Mq.Send("Hello!");
在这里建议你可以事先定义一个对象类,然后发送这个对象类的实例对象,这样以后无论在增加什么发送信息,只需在对象类中增加
相应的属性即可。

六、消息的接收和阅读

(1)同步接收消息

  接收消息的代码很简单:

 Mq.Receive();
        Mq.Receive(TimeSpan timeout); //设定超时时间
 Mq.ReceiveById(ID);
        Mq.Peek();
 
 通过Receive方法接收消息同时永久性地从队列中删除消息;
 通过Peek方法从队列中取出消息而不从队列中移除该消息。
 如果知道消息的标识符(ID),还可以通过ReceiveById方法和PeekById方法完成相应的操作。

(2)异步接受消息
  
   利用委托机制:

 MessQueue.ReceiveCompleted +=new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
 


(3)消息阅读

在应用程序能够阅读的消息和消息队列中的消息格式不同,应用程序发送出去的消息经过序列化以后才发送给了消息队列
而在接受端必须反序列化,利用下面的代码可以实现:

 public void mq_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e)
  {
   System.Messaging.Message m = MessQueue.EndReceive(e.AsyncResult);
   m.Formatter = new System.Messaging.XmlMessageFormatter(new string[]{"System.String,mscorlib"});
   Console.WriteLine("Message: " + (string)m.Body);
   MessQueue.BeginReceive() ;

  }

反序列化还有另一种写法:
 m.Formatter = new XmlMessageFormatter ( new Type [] { typeof (string) } );

 

七、由于消息队列的代码有些是固定不便的,所以把这些代码封装成一个类方便以后使用:

  1 None.gif using  System;
  2 None.gif using  System.Messaging;
  3 None.gif using  System.Threading;

  5 None.gif
  6 None.gif namespace  LoveStatusService
  7 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
  8ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
  9InBlock.gif    /// Summary description for Msmq.
 10ExpandedSubBlockEnd.gif    /// </summary>

 11InBlock.gif    public class Msmq
 12ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 13InBlock.gif        public Msmq()
 14ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 15InBlock.gif            //
 16InBlock.gif            // TODO: Add constructor logic here
 17InBlock.gif            //
 18ExpandedSubBlockEnd.gif        }

 19InBlock.gif
 20InBlock.gif        
 21InBlock.gif        private MessageQueue _messageQueue=null;
 22InBlock.gif        //最大并发线程数 
 23InBlock.gif        private static int MAX_WORKER_THREADS=Convert.ToInt32( System.Configuration.ConfigurationSettings.AppSettings["MAX_WORKER_THREADS"].ToString());
 24InBlock.gif        //Msmq路径
 25InBlock.gif        private static string MsmqPath=System.Configuration.ConfigurationSettings.AppSettings["LoveStatusMQPath"];
 26InBlock.gif        //等待句柄
 27InBlock.gif        private WaitHandle[] waitHandleArray = new WaitHandle[MAX_WORKER_THREADS];
 28InBlock.gif        //任务类型
 29InBlock.gif        //1. Send Email 2. Send Message  3. Send Email and Message
 30InBlock.gif        private string TaskType=System.Configuration.ConfigurationSettings.AppSettings["TaskType"];
 31InBlock.gif        public MessageQueue MessQueue
 32ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 33InBlock.gif            get
 34ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 35InBlock.gif            
 36InBlock.gif                if (_messageQueue==null)
 37ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 38InBlock.gif                    if(MessageQueue.Exists(MsmqPath))
 39ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
 40InBlock.gif                        _messageQueue = new MessageQueue(MsmqPath);    
 41ExpandedSubBlockEnd.gif                    }

 42InBlock.gif                    else
 43ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
 44InBlock.gif                        _messageQueue = MessageQueue.Create(MsmqPath);    
 45ExpandedSubBlockEnd.gif                    }
    
 46ExpandedSubBlockEnd.gif                }

 47InBlock.gif                
 48InBlock.gif
 49InBlock.gif                return _messageQueue;
 50ExpandedSubBlockEnd.gif            }

 51ExpandedSubBlockEnd.gif        }

 52InBlock.gif        
 53InBlock.gif
 54ContractedSubBlock.gifExpandedSubBlockStart.gif    Private Method#region Private Method
 55InBlock.gif
 56InBlock.gif        private void mq_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e)
 57ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 58InBlock.gif            MessageQueue mqq = (MessageQueue)sender;
 59InBlock.gif            System.Messaging.Message m = mqq.EndReceive(e.AsyncResult);
 60InBlock.gif            //m.Formatter = new System.Messaging.XmlMessageFormatter(new string[]{"System.String,mscorlib"});
 61ExpandedSubBlockStart.gifContractedSubBlock.gif            m.Formatter =new System.Messaging.XmlMessageFormatter(new Type[] dot.gif{typeof(UserObject)}) ;
 62InBlock.gif            //log.Info("Receive UserID: " + (string)m.Body) ;
 63InBlock.gif            UserObject obj=(UserObject)m.Body ;
 64InBlock.gif            long curUserId=obj.curUserID ;
 65InBlock.gif            long oppUserId=obj.oppUserID;
 66InBlock.gif            string curUserName=obj.curUserName;
 67InBlock.gif            string oppUserName=obj.oppUserName;
 68InBlock.gif            string curEmail=obj.curEmail ;
 69InBlock.gif            string oppEmail=obj.oppEmail;
 70InBlock.gif            string subject =obj.subject ;
 71InBlock.gif            string body=obj.body ;
 72InBlock.gif            //AppLog.log.Info("curUserId:"+curUserId) ;
 73InBlock.gif            //AppLog.log.Info("oppUserId:"+oppUserId) ;
 74InBlock.gif            AppLog.log.Info("==type="+TaskType) ;
 75InBlock.gif            switch(TaskType)
 76ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 77InBlock.gif                //Email
 78InBlock.gif                case "1":
 79InBlock.gif                    EmailForMQ.SendEmailForLoveStatus(curEmail,oppEmail,curUserName,oppUserName,subject) ;
 80InBlock.gif                    AppLog.log.Info("==Send to=="+oppEmail) ;
 81InBlock.gif                    break;
 82InBlock.gif                //Message
 83InBlock.gif                case "2":
 84InBlock.gif                    MessageForMQ.SendMessage(curUserId,oppUserId,subject,body) ;
 85InBlock.gif                    AppLog.log.Info("==Send Msg to=="+oppUserId) ;
 86InBlock.gif                    break;
 87InBlock.gif                //Email and Message        
 88InBlock.gif                case "3":
 89InBlock.gif                    EmailForMQ.SendEmailForLoveStatus(curEmail,oppEmail,curUserName,oppUserName,subject) ;
 90InBlock.gif                    AppLog.log.Info("==Send to=="+oppEmail) ;
 91InBlock.gif                    MessageForMQ.SendMessage(curUserId,oppUserId,subject,body) ;
 92InBlock.gif                    AppLog.log.Info("==Send Msg to=="+oppUserId) ;
 93InBlock.gif                    break;
 94InBlock.gif                default:
 95InBlock.gif                    break;
 96InBlock.gif
 97ExpandedSubBlockEnd.gif            }

 98InBlock.gif            mqq.BeginReceive() ;
 99InBlock.gif
100ExpandedSubBlockEnd.gif        }

101InBlock.gif
102ExpandedSubBlockEnd.gif    #endregion

103InBlock.gif
104ContractedSubBlock.gifExpandedSubBlockStart.gif    Public Method#region Public Method
105InBlock.gif
106InBlock.gif        //一个将对象发送到队列的方法,这里发送的是对象
107InBlock.gif        public void SendUserIDToMQ(object arr)
108ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
109InBlock.gif            MessQueue.Send(arr) ;
110InBlock.gif            Console.WriteLine("Ok") ;
111InBlock.gif            Console.Read() ;
112ExpandedSubBlockEnd.gif        }

113InBlock.gif
114InBlock.gif        //同步接受队列内容的方法
115InBlock.gif        public void ReceiveFromMQ()
116ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
117InBlock.gif            Message ms=new Message() ;
118InBlock.gif            
119InBlock.gif            //ms=MessQueue.Peek(); 
120InBlock.gif            try
121ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
122InBlock.gif                ms=MessQueue.Receive(new TimeSpan(0,0,5));
123InBlock.gif                if(ms!=null)
124ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
125ExpandedSubBlockStart.gifContractedSubBlock.gif                    ms.Formatter = new XmlMessageFormatter ( new Type [] dot.giftypeof (string) } );
126InBlock.gif                    AppLog.log.Info((string)ms.Body)  ; 
127ExpandedSubBlockEnd.gif                }

128ExpandedSubBlockEnd.gif            }

129InBlock.gif            catch(Exception ex)
130ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
131InBlock.gif                
132ExpandedSubBlockEnd.gif            }

133InBlock.gif            
134InBlock.gif        
135ExpandedSubBlockEnd.gif        }

136InBlock.gif
137InBlock.gif        //开始监听工作线程
138InBlock.gif        public  void startListen()
139ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
140InBlock.gif            AppLog.log.Info("--Thread--"+MAX_WORKER_THREADS) ;
141InBlock.gif            MessQueue.ReceiveCompleted +=new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
142InBlock.gif            
143InBlock.gif            //异步方式,并发
144InBlock.gif            
145InBlock.gif            for(int i=0; i<MAX_WORKER_THREADS; i++)
146ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
147InBlock.gif                // Begin asynchronous operations.
148InBlock.gif                waitHandleArray[i] = MessQueue.BeginReceive().AsyncWaitHandle;
149ExpandedSubBlockEnd.gif            }

150InBlock.gif
151InBlock.gif            AppLog.log.Info("------Start Listen--------") ;
152InBlock.gif
153InBlock.gif            return;
154InBlock.gif
155ExpandedSubBlockEnd.gif        }

156InBlock.gif
157InBlock.gif 
158InBlock.gif        //停止监听工作线程
159InBlock.gif        public void stopListen()
160ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
161InBlock.gif
162InBlock.gif            for(int i=0;i<waitHandleArray.Length;i++)
163ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
164InBlock.gif
165InBlock.gif                try
166ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
167InBlock.gif                    waitHandleArray[i].Close();
168ExpandedSubBlockEnd.gif                }

169InBlock.gif                catch
170ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
171InBlock.gif                    AppLog.log.Info("---waitHandleArray[i].Close() Error!-----") ;
172ExpandedSubBlockEnd.gif                }

173InBlock.gif
174ExpandedSubBlockEnd.gif            }

175InBlock.gif
176InBlock.gif            try
177ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
178InBlock.gif                // Specify to wait for all operations to return.
179InBlock.gif                WaitHandle.WaitAll(waitHandleArray,1000,false);
180ExpandedSubBlockEnd.gif            }

181InBlock.gif            catch
182ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
183InBlock.gif                AppLog.log.Info("---WaitHandle.WaitAll Error!-----") ;
184ExpandedSubBlockEnd.gif            }

185InBlock.gif            AppLog.log.Info("------Stop Listen--------") ;
186InBlock.gif
187ExpandedSubBlockEnd.gif        }

188InBlock.gif
189ExpandedSubBlockEnd.gif    #endregion

190InBlock.gif    
191InBlock.gif    
192InBlock.gif
193InBlock.gif    
194ExpandedSubBlockEnd.gif    }

195ExpandedBlockEnd.gif}

196 None.gif

UserObject的代码

  1 None.gif using  System;
  2 None.gif
  3 None.gif namespace  Goody9807
  4 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
  5ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
  6InBlock.gif    /// 用与在MQ上传输数据的对象
  7ExpandedSubBlockEnd.gif    /// </summary>

  8InBlock.gif    public class UserObject
  9ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 10InBlock.gif        public UserObject()
 11ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 12InBlock.gif            //
 13InBlock.gif            // TODO: Add constructor logic here
 14InBlock.gif            //
 15ExpandedSubBlockEnd.gif        }

 16InBlock.gif
 17InBlock.gif        private long _curUserID;
 18InBlock.gif        public long curUserID
 19ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 20InBlock.gif            get
 21ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 22InBlock.gif                return _curUserID;
 23ExpandedSubBlockEnd.gif            }

 24InBlock.gif            set
 25ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 26InBlock.gif                _curUserID=value;
 27ExpandedSubBlockEnd.gif            }

 28ExpandedSubBlockEnd.gif        }

 29InBlock.gif
 30InBlock.gif        private  string _curUserName="";
 31InBlock.gif        public string curUserName
 32ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 33InBlock.gif            get
 34ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 35InBlock.gif                return _curUserName;
 36ExpandedSubBlockEnd.gif            }

 37InBlock.gif            set
 38ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 39InBlock.gif                _curUserName=value;
 40ExpandedSubBlockEnd.gif            }

 41ExpandedSubBlockEnd.gif        }

 42InBlock.gif
 43InBlock.gif        private string _curEmail="";
 44InBlock.gif        public string curEmail
 45ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 46InBlock.gif            get
 47ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 48InBlock.gif                return _curEmail;
 49ExpandedSubBlockEnd.gif            }

 50InBlock.gif            set
 51ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 52InBlock.gif                _curEmail=value;
 53ExpandedSubBlockEnd.gif            }

 54ExpandedSubBlockEnd.gif        }

 55InBlock.gif
 56InBlock.gif
 57InBlock.gif        private long _oppUserID;
 58InBlock.gif        public long oppUserID
 59ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 60InBlock.gif            get
 61ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 62InBlock.gif                return _oppUserID;
 63ExpandedSubBlockEnd.gif            }

 64InBlock.gif            set
 65ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 66InBlock.gif                _oppUserID=value;
 67ExpandedSubBlockEnd.gif            }

 68ExpandedSubBlockEnd.gif        }

 69InBlock.gif
 70InBlock.gif        private  string _oppUserName="";
 71InBlock.gif        public string oppUserName
 72ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 73InBlock.gif            get
 74ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 75InBlock.gif                return _oppUserName;
 76ExpandedSubBlockEnd.gif            }

 77InBlock.gif            set
 78ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 79InBlock.gif                _oppUserName=value;
 80ExpandedSubBlockEnd.gif            }

 81ExpandedSubBlockEnd.gif        }

 82InBlock.gif
 83InBlock.gif        private string _oppEmail="";
 84InBlock.gif        public string oppEmail
 85ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 86InBlock.gif            get
 87ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 88InBlock.gif                return _oppEmail;
 89ExpandedSubBlockEnd.gif            }

 90InBlock.gif            set
 91ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 92InBlock.gif                _oppEmail=value;
 93ExpandedSubBlockEnd.gif            }

 94ExpandedSubBlockEnd.gif        }

 95InBlock.gif
 96InBlock.gif        private string _subject ="";
 97InBlock.gif        public string subject
 98ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 99InBlock.gif            get
100ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
101InBlock.gif                return _subject;
102ExpandedSubBlockEnd.gif            }

103InBlock.gif            set
104ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
105InBlock.gif                _subject=value;
106ExpandedSubBlockEnd.gif            }

107ExpandedSubBlockEnd.gif        }

108InBlock.gif
109InBlock.gif        private string _body="";
110InBlock.gif        public string body
111ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
112InBlock.gif            get
113ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
114InBlock.gif                return _body;
115ExpandedSubBlockEnd.gif            }

116InBlock.gif            set
117ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
118InBlock.gif                _body=value;
119ExpandedSubBlockEnd.gif            }

120ExpandedSubBlockEnd.gif        }

121ExpandedSubBlockEnd.gif    }

122ExpandedBlockEnd.gif}

123 None.gif

另一个同事写的封装类

ContractedBlock.gif ExpandedBlockStart.gif
  1None.gifusing System;
  2None.gif
  3None.gifusing System.Threading;
  4None.gif
  5None.gifusing System.Messaging;
  6None.gif
  7None.gif 
  8None.gif
  9None.gifnamespace Wapdm.SmsApp
 10None.gif
 11ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 12InBlock.gif
 13ExpandedSubBlockStart.gifContractedSubBlock.gif     /**//// <summary>
 14InBlock.gif
 15InBlock.gif     /// <para>
 16InBlock.gif
 17InBlock.gif     /// A Logger implementation that writes messages to a message queue.
 18InBlock.gif
 19InBlock.gif     /// The default event formatter used is an instance of XMLEventFormatter
 20InBlock.gif
 21InBlock.gif     /// </para>
 22InBlock.gif
 23ExpandedSubBlockEnd.gif     /// </summary>

 24InBlock.gif
 25InBlock.gif     public sealed class MsgQueue 
 26InBlock.gif
 27ExpandedSubBlockStart.gifContractedSubBlock.gif     dot.gif{
 28InBlock.gif
 29InBlock.gif 
 30InBlock.gif
 31InBlock.gif         private const string BLANK_STRING                   = "";
 32InBlock.gif
 33InBlock.gif         private const string PERIOD                         = @".\private$";  //".";
 34InBlock.gif
 35InBlock.gif         private const string ELLIPSIS                       = "dot.gif";    
 36InBlock.gif
 37InBlock.gif    
 38InBlock.gif
 39InBlock.gif         private string serverAddress;
 40InBlock.gif
 41InBlock.gif         private string queueName;
 42InBlock.gif
 43InBlock.gif         private string queuePath;
 44InBlock.gif
 45InBlock.gif         
 46InBlock.gif
 47InBlock.gif         private bool IsContextEnabled;  
 48InBlock.gif
 49InBlock.gif    
 50InBlock.gif
 51InBlock.gif         private MessageQueue queue;
 52InBlock.gif
 53InBlock.gif    
 54InBlock.gif
 55InBlock.gif         private object queueMonitor                         = new object();
 56InBlock.gif
 57InBlock.gif    
 58InBlock.gif
 59ExpandedSubBlockStart.gifContractedSubBlock.gif         private MsgQueue() dot.gif{}
 60InBlock.gif
 61InBlock.gif 
 62InBlock.gif
 63InBlock.gif         public static MsgQueue mq = null;
 64InBlock.gif
 65InBlock.gif         public static WaitHandle[] waitHandleArray = new WaitHandle[Util.MAX_WORKER_THREADS];
 66InBlock.gif
 67InBlock.gif     
 68InBlock.gif
 69InBlock.gif         public MsgQueue(string _serverAddress, string _queueName, string _summaryPattern) 
 70InBlock.gif
 71ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
 72InBlock.gif
 73InBlock.gif              if ((_serverAddress == null|| (_queueName == null|| (_summaryPattern == null)) 
 74InBlock.gif
 75ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
 76InBlock.gif
 77InBlock.gif                   throw new ArgumentNullException();
 78InBlock.gif
 79ExpandedSubBlockEnd.gif              }

 80InBlock.gif
 81InBlock.gif              ServerAddress = _serverAddress;
 82InBlock.gif
 83InBlock.gif              QueueName = _queueName;
 84InBlock.gif
 85InBlock.gif              IsContextEnabled = true;             
 86InBlock.gif
 87ExpandedSubBlockEnd.gif         }

 88InBlock.gif
 89InBlock.gif    
 90InBlock.gif
 91InBlock.gif         public MsgQueue(string _serverAddress, string _queueName) 
 92InBlock.gif
 93ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
 94InBlock.gif
 95InBlock.gif              if ((_serverAddress == null|| (_queueName == null)) 
 96InBlock.gif
 97ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
 98InBlock.gif
 99InBlock.gif                   throw new ArgumentNullException();
100InBlock.gif
101ExpandedSubBlockEnd.gif              }

102InBlock.gif
103InBlock.gif              ServerAddress = _serverAddress;
104InBlock.gif
105InBlock.gif              QueueName = _queueName;
106InBlock.gif
107InBlock.gif              IsContextEnabled = true;
108InBlock.gif
109ExpandedSubBlockEnd.gif         }

110InBlock.gif
111InBlock.gif    
112InBlock.gif
113InBlock.gif         public MsgQueue(string _queueName) 
114InBlock.gif
115ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
116InBlock.gif
117InBlock.gif              if (_queueName == null
118InBlock.gif
119ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
120InBlock.gif
121InBlock.gif                   throw new ArgumentNullException();
122InBlock.gif
123ExpandedSubBlockEnd.gif              }

124InBlock.gif
125InBlock.gif              serverAddress = PERIOD;
126InBlock.gif
127InBlock.gif              QueueName = _queueName;
128InBlock.gif
129InBlock.gif              IsContextEnabled = true;             
130InBlock.gif
131InBlock.gif              if ( IsContextEnabled == false )
132InBlock.gif
133InBlock.gif                   throw new ArgumentNullException();
134InBlock.gif
135ExpandedSubBlockEnd.gif         }

136InBlock.gif
137InBlock.gif    
138InBlock.gif
139InBlock.gif         public string ServerAddress 
140InBlock.gif
141ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
142InBlock.gif
143InBlock.gif              get 
144InBlock.gif
145ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
146InBlock.gif
147InBlock.gif                   return serverAddress;
148InBlock.gif
149ExpandedSubBlockEnd.gif              }

150InBlock.gif
151InBlock.gif              set 
152InBlock.gif
153ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
154InBlock.gif
155InBlock.gif                   if (value == null
156InBlock.gif
157ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
158InBlock.gif
159InBlock.gif                       value = PERIOD;
160InBlock.gif
161ExpandedSubBlockEnd.gif                   }

162InBlock.gif
163InBlock.gif                   value = value.Trim();
164InBlock.gif
165InBlock.gif                   if (value.Equals(BLANK_STRING)) 
166InBlock.gif
167ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
168InBlock.gif
169InBlock.gif                       throw new ArgumentException("Invalid value (must contain non-whitespace characters)");
170InBlock.gif
171ExpandedSubBlockEnd.gif                  }

172InBlock.gif
173InBlock.gif                   lock (queueMonitor) 
174InBlock.gif
175ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
176InBlock.gif
177InBlock.gif                       serverAddress = value;
178InBlock.gif
179InBlock.gif                       queuePath = serverAddress + '\\' + queueName;
180InBlock.gif
181InBlock.gif                       InitializeQueue();
182InBlock.gif
183ExpandedSubBlockEnd.gif                   }

184InBlock.gif
185ExpandedSubBlockEnd.gif              }

186InBlock.gif
187ExpandedSubBlockEnd.gif         }

188InBlock.gif
189InBlock.gif 
190InBlock.gif
191InBlock.gif         public string QueueName 
192InBlock.gif
193ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
194InBlock.gif
195InBlock.gif              get 
196InBlock.gif
197ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
198InBlock.gif
199InBlock.gif                   return queueName;
200InBlock.gif
201ExpandedSubBlockEnd.gif              }

202InBlock.gif
203InBlock.gif              set 
204InBlock.gif
205ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
206InBlock.gif
207InBlock.gif                   if (value == null
208InBlock.gif
209ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
210InBlock.gif
211InBlock.gif                       throw new ArgumentNullException();
212InBlock.gif
213ExpandedSubBlockEnd.gif                   }

214InBlock.gif
215InBlock.gif                   value = value.Trim();
216InBlock.gif
217InBlock.gif                   if (value.Equals(BLANK_STRING)) 
218InBlock.gif
219ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
220InBlock.gif
221InBlock.gif                       throw new ArgumentException("Invalid value (must contain non-whitespace characters)");
222InBlock.gif
223ExpandedSubBlockEnd.gif                   }

224InBlock.gif
225InBlock.gif                   lock (queueMonitor) 
226InBlock.gif
227ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
228InBlock.gif
229InBlock.gif                       queueName = value;
230InBlock.gif
231InBlock.gif                       queuePath = serverAddress + '\\' + queueName;
232InBlock.gif
233InBlock.gif                       InitializeQueue();
234InBlock.gif
235ExpandedSubBlockEnd.gif                   }

236InBlock.gif
237ExpandedSubBlockEnd.gif              }

238InBlock.gif
239ExpandedSubBlockEnd.gif         }

240InBlock.gif
241InBlock.gif    
242InBlock.gif
243InBlock.gif         private void InitializeQueue() 
244InBlock.gif
245ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
246InBlock.gif
247InBlock.gif              lock (queueMonitor) 
248InBlock.gif
249ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{             
250InBlock.gif
251InBlock.gif                   if (queue != null
252InBlock.gif
253ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
254InBlock.gif
255ExpandedSubBlockStart.gifContractedSubBlock.gif                       try dot.gif{ queue.Close(); } 
256InBlock.gif
257ExpandedSubBlockStart.gifContractedSubBlock.gif                       catch dot.gif{}
258InBlock.gif
259InBlock.gif                       queue = null;
260InBlock.gif
261ExpandedSubBlockEnd.gif                   }

262InBlock.gif
263InBlock.gif 
264InBlock.gif
265InBlock.gif                   try 
266InBlock.gif
267ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
268InBlock.gif
269InBlock.gif                       if(!MessageQueue.Exists(queuePath))
270InBlock.gif
271InBlock.gif                            MessageQueue.Create(queuePath);
272InBlock.gif
273ExpandedSubBlockEnd.gif                   }
 
274InBlock.gif
275ExpandedSubBlockStart.gifContractedSubBlock.gif                   catch dot.gif{}
276InBlock.gif
277InBlock.gif                   try 
278InBlock.gif
279ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
280InBlock.gif
281InBlock.gif                       queue = new MessageQueue(queuePath);
282InBlock.gif
283InBlock.gif                       queue.SetPermissions("EveryOne",MessageQueueAccessRights.FullControl);
284InBlock.gif
285ExpandedSubBlockStart.gifContractedSubBlock.gif                       queue.Formatter = new XmlMessageFormatter(new Type[] dot.gif{typeof(MoMsg)});
286InBlock.gif
287ExpandedSubBlockEnd.gif                   }
 
288InBlock.gif
289InBlock.gif                   catch (Exception e) 
290InBlock.gif
291ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
292InBlock.gif
293ExpandedSubBlockStart.gifContractedSubBlock.gif                       try dot.gif{ queue.Close(); } 
294InBlock.gif
295ExpandedSubBlockStart.gifContractedSubBlock.gif                       catch dot.gif{}
296InBlock.gif
297InBlock.gif                       queue = null;
298InBlock.gif
299InBlock.gif                       throw new ApplicationException("Couldn't open queue at '" + queuePath + "': " + e.GetType().FullName + "" + e.Message);
300InBlock.gif
301ExpandedSubBlockEnd.gif                   }

302InBlock.gif
303InBlock.gif 
304InBlock.gif
305ExpandedSubBlockEnd.gif              }

306InBlock.gif
307ExpandedSubBlockEnd.gif         }

308InBlock.gif
309InBlock.gif    
310InBlock.gif
311InBlock.gif         private  void AcquireResources() 
312InBlock.gif
313ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
314InBlock.gif
315InBlock.gif              InitializeQueue();
316InBlock.gif
317ExpandedSubBlockEnd.gif         }

318InBlock.gif
319InBlock.gif    
320InBlock.gif
321InBlock.gif         public  void ReleaseResources() 
322InBlock.gif
323ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
324InBlock.gif
325InBlock.gif              lock (queueMonitor) 
326InBlock.gif
327ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
328InBlock.gif
329InBlock.gif                   if (queue != null
330InBlock.gif
331ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
332InBlock.gif
333InBlock.gif                       try 
334InBlock.gif
335ExpandedSubBlockStart.gifContractedSubBlock.gif                       dot.gif{
336InBlock.gif
337InBlock.gif                            queue.Close();
338InBlock.gif
339ExpandedSubBlockEnd.gif                       }
 
340InBlock.gif
341ExpandedSubBlockStart.gifContractedSubBlock.gif                       catch dot.gif{}
342InBlock.gif
343InBlock.gif                       queue = null;
344InBlock.gif
345ExpandedSubBlockEnd.gif                   }

346InBlock.gif
347ExpandedSubBlockEnd.gif              }
    
348InBlock.gif
349ExpandedSubBlockEnd.gif         }

350InBlock.gif
351InBlock.gif    
352InBlock.gif
353InBlock.gif         //阻塞方式
354InBlock.gif
355InBlock.gif         public MoMsg Read( ) 
356InBlock.gif
357ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
358InBlock.gif
359InBlock.gif              MoMsg _event = null;             
360InBlock.gif
361InBlock.gif              lock (queueMonitor) 
362InBlock.gif
363ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
364InBlock.gif
365InBlock.gif                   if (queue == null
366InBlock.gif
367ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
368InBlock.gif
369InBlock.gif                       InitializeQueue();
370InBlock.gif
371ExpandedSubBlockEnd.gif                   }

372InBlock.gif
373InBlock.gif                   try 
374InBlock.gif
375ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
376InBlock.gif
377InBlock.gif                       Message message = queue.Receive( new TimeSpan(0,0,1) );//等待10秒
378InBlock.gif
379InBlock.gif                       _event = (MoMsg) (message.Body);
380InBlock.gif
381InBlock.gif                       return _event;
382InBlock.gif
383ExpandedSubBlockEnd.gif                   }

384InBlock.gif
385InBlock.gif                   catch (Exception ) 
386InBlock.gif
387ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
388InBlock.gif
389ExpandedSubBlockStart.gifContractedSubBlock.gif                       try dot.gif{ queue.Close(); } 
390InBlock.gif
391ExpandedSubBlockStart.gifContractedSubBlock.gif                       catch dot.gif{}
392InBlock.gif
393InBlock.gif                       queue = null;
394InBlock.gif
395ExpandedSubBlockEnd.gif                   }
            
396InBlock.gif
397ExpandedSubBlockEnd.gif              }

398InBlock.gif
399InBlock.gif              return null;
400InBlock.gif
401ExpandedSubBlockEnd.gif         }

402InBlock.gif
403InBlock.gif 
404InBlock.gif
405InBlock.gif         public void Write(MoMsg _event) 
406InBlock.gif
407ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
408InBlock.gif
409InBlock.gif              if (_event == null
410InBlock.gif
411ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
412InBlock.gif
413InBlock.gif                   return;
414InBlock.gif
415ExpandedSubBlockEnd.gif              }

416InBlock.gif
417InBlock.gif              lock (queueMonitor) 
418InBlock.gif
419ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
420InBlock.gif
421InBlock.gif                   try 
422InBlock.gif
423ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
424InBlock.gif
425InBlock.gif                       if (queue == null
426InBlock.gif
427ExpandedSubBlockStart.gifContractedSubBlock.gif                       dot.gif{
428InBlock.gif
429InBlock.gif                            InitializeQueue();
430InBlock.gif
431ExpandedSubBlockEnd.gif                       }

432InBlock.gif
433InBlock.gif                   
434InBlock.gif
435InBlock.gif                       Message message = new Message();
436InBlock.gif
437InBlock.gif                       message.Priority = _event.Priority;
438InBlock.gif
439InBlock.gif                       message.Recoverable = true;
440InBlock.gif
441InBlock.gif                       message.Body = _event; //eventFormatter.Format(_event);
442InBlock.gif
443InBlock.gif 
444InBlock.gif
445InBlock.gif                       queue.Send(message);
446InBlock.gif
447ExpandedSubBlockEnd.gif                   }

448InBlock.gif
449InBlock.gif                   catch (Exception e)
450InBlock.gif
451ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
452InBlock.gif
453ExpandedSubBlockStart.gifContractedSubBlock.gif                       try dot.gif{ queue.Close(); } 
454InBlock.gif
455ExpandedSubBlockStart.gifContractedSubBlock.gif                       catch dot.gif{}
456InBlock.gif
457InBlock.gif                       queue = null;
458InBlock.gif
459InBlock.gif                       Util.Log.log("Couldn't write Message (" + e.GetType().FullName + "" + e.Message + ")");
460InBlock.gif
461ExpandedSubBlockEnd.gif                   }
            
462InBlock.gif
463ExpandedSubBlockEnd.gif              }

464InBlock.gif
465ExpandedSubBlockEnd.gif         }

466InBlock.gif
467InBlock.gif 
468InBlock.gif
469InBlock.gif         public static bool statusTest()
470InBlock.gif
471ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
472InBlock.gif
473InBlock.gif              bool reValue = false;
474InBlock.gif
475InBlock.gif              try
476InBlock.gif
477ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
478InBlock.gif
479InBlock.gif                   MessageEnumerator re = mq.queue.GetMessageEnumerator();
480InBlock.gif
481InBlock.gif                   bool rev = re.MoveNext();
482InBlock.gif
483InBlock.gif                   reValue = true;
484InBlock.gif
485ExpandedSubBlockEnd.gif              }

486InBlock.gif
487InBlock.gif              catch
488InBlock.gif
489ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
490InBlock.gif
491InBlock.gif                   reValue = false;
492InBlock.gif
493ExpandedSubBlockEnd.gif              }

494InBlock.gif
495InBlock.gif 
496InBlock.gif
497InBlock.gif              return reValue;
498InBlock.gif
499ExpandedSubBlockEnd.gif         }

500InBlock.gif
501InBlock.gif 
502InBlock.gif
503InBlock.gif         public static void startListen()
504InBlock.gif
505ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
506InBlock.gif
507InBlock.gif              mq = new MsgQueue(Util.MqName);
508InBlock.gif
509InBlock.gif 
510InBlock.gif
511InBlock.gif              mq.queue.ReceiveCompleted +=new ReceiveCompletedEventHandler(queue_ReceiveCompleted);
512InBlock.gif
513InBlock.gif              
514InBlock.gif
515InBlock.gif              //异步方式,并发
516InBlock.gif
517InBlock.gif              for(int i=0; i<Util.MAX_WORKER_THREADS; i++)
518InBlock.gif
519ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
520InBlock.gif
521InBlock.gif                   // Begin asynchronous operations.
522InBlock.gif
523InBlock.gif                   waitHandleArray[i] = 
524InBlock.gif
525InBlock.gif                       mq.queue.BeginReceive().AsyncWaitHandle;
526InBlock.gif
527ExpandedSubBlockEnd.gif              }

528InBlock.gif
529InBlock.gif 
530InBlock.gif
531InBlock.gif              return;
532InBlock.gif
533ExpandedSubBlockEnd.gif         }

534InBlock.gif
535InBlock.gif 
536InBlock.gif
537InBlock.gif         public static void stopListen()
538InBlock.gif
539ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
540InBlock.gif
541InBlock.gif 
542InBlock.gif
543InBlock.gif              for(int i=0;i<waitHandleArray.Length;i++)
544InBlock.gif
545ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
546InBlock.gif
547InBlock.gif                   try
548InBlock.gif
549ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
550InBlock.gif
551InBlock.gif                       waitHandleArray[i].Close();
552InBlock.gif
553ExpandedSubBlockEnd.gif                   }

554InBlock.gif
555InBlock.gif                   catch
556InBlock.gif
557ExpandedSubBlockStart.gifContractedSubBlock.gif                   dot.gif{
558InBlock.gif
559InBlock.gif                       //忽略错误
560InBlock.gif
561ExpandedSubBlockEnd.gif                   }

562InBlock.gif
563ExpandedSubBlockEnd.gif              }

564InBlock.gif
565InBlock.gif 
566InBlock.gif
567InBlock.gif              try
568InBlock.gif
569ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
570InBlock.gif
571InBlock.gif                  // Specify to wait for all operations to return.
572InBlock.gif
573InBlock.gif                   WaitHandle.WaitAll(waitHandleArray,1000,false);
574InBlock.gif
575ExpandedSubBlockEnd.gif              }

576InBlock.gif
577InBlock.gif              catch
578InBlock.gif
579ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
580InBlock.gif
581InBlock.gif                   //忽略错误
582InBlock.gif
583ExpandedSubBlockEnd.gif              }

584InBlock.gif
585ExpandedSubBlockEnd.gif         }

586InBlock.gif
587InBlock.gif 
588InBlock.gif
589InBlock.gif         private static void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
590InBlock.gif
591ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
592InBlock.gif
593InBlock.gif              // Connect to the queue.
594InBlock.gif
595InBlock.gif              MessageQueue mqq = (MessageQueue)sender;
596InBlock.gif
597InBlock.gif 
598InBlock.gif
599InBlock.gif              // End the asynchronous Receive operation.
600InBlock.gif
601InBlock.gif              Message m = mqq.EndReceive(e.AsyncResult);
602InBlock.gif
603InBlock.gif 
604InBlock.gif
605InBlock.gif              Util.ProcessMo((MoMsg)(m.Body));
606InBlock.gif
607InBlock.gif 
608InBlock.gif
609InBlock.gif              if(Util.isRunning)
610InBlock.gif
611ExpandedSubBlockStart.gifContractedSubBlock.gif              dot.gif{
612InBlock.gif
613InBlock.gif                   // Restart the asynchronous Receive operation.
614InBlock.gif
615InBlock.gif                   mqq.BeginReceive();
616InBlock.gif
617ExpandedSubBlockEnd.gif              }

618InBlock.gif
619InBlock.gif            
620InBlock.gif
621InBlock.gif              return;
622InBlock.gif
623ExpandedSubBlockEnd.gif         }

624InBlock.gif
625ExpandedSubBlockEnd.gif     }

626InBlock.gif
627ExpandedBlockEnd.gif}

628None.gif
629None.gif



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值