MSMQ implements the principle that the sender of a message places the information he wants to send into a container (what we call a message) and then saves it to a message queue in a system's public space A local or offsite message receiver is then taken out of the queue to process messages sent to it.
I personally understand that you can think of him as a kind of, after the data is packaged, sent to a place, the program can also go to the packaging of the program, the mechanism of the queue is not speaking, the concurrency problem is gone. Oh.
On the code:
First of all
usingsystem.messaging; Public classMsmqmanagerhelper {Private ReadOnly string_path; PrivateMessageQueue _msmq; PublicMsmqmanagerhelper () {_path=@". \private$\ a name for the service instance";//This is the way the native instance if(!messagequeue.exists (_path)) {messagequeue.create (_path); } _msmq=NewMessageQueue (_path); } /// <summary> ///Send Message Queue/// </summary> /// <param name= "Msmqindex" >Message Queuing Entity</param> /// <returns></returns> Public voidSend (ObjectMsmqindex) {_msmq. Send (NewMessage (Msmqindex,NewBinaryMessageFormatter ())); } /// <summary> ///Receive Message Queuing, delete queue/// </summary> /// <returns></returns> Public ObjectReceiveandremove () {ObjectMsmqindex =NULL; _msmq. Formatter=NewBinaryMessageFormatter (); Message msg=NULL; Try{msg= _msmq. Receive (NewTimeSpan (0,0,1)); } Catch(Exception ex) {Console.WriteLine (ex). Message); //logging and sending email alerts } if(msg! =NULL) {Msmqindex=Msg. Body; } returnMsmqindex; } /// <summary> ///releasing a Message Queuing instance/// </summary> Public voidDispose () {if(_MSMQ! =NULL) {_msmq. Close (); _msmq. Dispose (); _MSMQ=NULL; } } }
View Code
The above is a helper class, and the calling method is described below.
classProgram {Static voidMain () {varMMH =NewMsmqmanagerhelper (); Console.WriteLine ("Test MSMQ Work"); Console.WriteLine ("Send Message"); stringReceivekey =Console.ReadLine (); Try { varm=NewModel (); M.id=1; M.name=Receivekey; Mmh. Send (m); } Catch(Exception ex) {Console.WriteLine (ex). ToString ()); } console.readline (); Console.WriteLine ("start accepting Messages ..."); while(true) { Objectobj =MMH. Receiveandremove (); if(obj! =NULL) { varitem =(Model) obj; Console.WriteLine (Item.id+":"+item. Name); } Else { Break; } thread.sleep ( $); } console.readline (); } }
View Code
Original link: http://www.cnblogs.com/isdavid/archive/2012/08/16/2642867.html
"Go" MSMQ Microsoft Message Queue Simple Example