一、创建一个队列 if ( ! MessageQueue.Exists( " .\\Private$\\newPublicQueue " )) { // MessageQueue.Create(".\\newPublicQueue");//创建一个公共队列 MessageQueue.Create(".\\Private$\\newPublicQueue");//创建一个私有队列 } 二、同步接收消息 1)接收消息,接受成功后删除 MessageQueue queue = new MessageQueue( " .\\Private$\\newPublicQueue " ); Message message = queue.Receive(); // Receive message, 同步的Receive方法阻塞当前执行线程,直到一个message可以得到,接收之后就删除 message.Formatter = new XmlMessageFormatter( new Type[] { typeof(string) } ); this .TextBox2.Text = message.Body.ToString(); 2)接受消息,接收成功后保留 MessageQueue queue = new MessageQueue( " .\\Private$\\newPublicQueue " ); Message message = queue.Peek(); // 异步接收消息。接收之后不删除 message.Formatter = new XmlMessageFormatter( new Type[] { typeof(string) } ); this .TextBox4.Text = message.Body.ToString(); 三、异步接收消息 1)接收消息,接受成功后删除 MessageQueue queue = new MessageQueue( " .\\Private$\\newPublicQueue " ); // queue.BeginReceive(); // 异步接收消息。接收之后就删除 // 给接收结束加一个委托 queue.ReceiveCompleted += new ReceiveCompletedEventHandler(MyReceiveCompleted); // 开始接收 queue.BeginReceive(); private static void MyReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult) { try { // Connect to the queue. MessageQueue mq = (MessageQueue)source; // End the asynchronous receive operation. Message m = mq.EndReceive(asyncResult.AsyncResult); m.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); System.IO.StreamWriter fs1 = new System.IO.StreamWriter("e:\\11.txt", false, System.Text.Encoding.Default);// System.IO.File.CreateText("c:\\testAsyn.txt"); fs1.WriteLine(m.Body.ToString()); fs1.Close(); count += 1; if (count == 2) { signal.Set(); } // Restart the asynchronous receive operation. mq.BeginReceive(); } catch(MessageQueueException) { // Handle sources of MessageQueueException. } return; } 2)接受消息,接收成功后保留 MessageQueue queue1 = new MessageQueue( " .\\Private$\\newPublicQueue " ); // queue.BeginReceive(); // 异步接收消息。接收之后就删除 // 给接收结束加一个委托 queue1.PeekCompleted += new PeekCompletedEventHandler(PeekMyReceiveCompleted); // 开始接收 queue1.BeginPeek(); private static void PeekMyReceiveCompleted(Object source, PeekCompletedEventArgs asyncResult) { try { // Connect to the queue. MessageQueue mq = (MessageQueue)source; // End the asynchronous receive operation. Message m = mq.EndPeek(asyncResult.AsyncResult); m.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); System.IO.StreamWriter fs1 = new System.IO.StreamWriter("e:\\22.txt", false, System.Text.Encoding.Default);// System.IO.File.CreateText("c:\\testAsyn.txt"); fs1.WriteLine(m.Body.ToString()); fs1.Close(); count += 1; if (count == 2) { signal.Set(); } // Restart the asynchronous receive operation. mq.BeginPeek(); } catch (MessageQueueException) { // Handle sources of MessageQueueException. } return; } 完整代码下载 转载于:https://www.cnblogs.com/gjahead/archive/2007/08/05/843934.html