# 简单的同步MSMQ```cs using System; using System.Messaging; using System.Windows.Forms; namespace MSMQExample { /// /// 一个简单的MSMQ例子,目前只是同步操作。 /// public partial class Form1 : Form { private string queuestring = @".\Private$\MyQueue"; private int times = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } /// /// /// /// private void btn_create_Click(object sender, EventArgs e) { try { if (!MessageQueue.Exists(queuestring)) { MessageQueue.Create(queuestring); } MessageQueue queue = new MessageQueue(queuestring); lbl_msg1.Text = string.Format("path={0}\nformat={1}", queue.Path, queue.FormatName); } catch (MessageQueueException ex) { lbl_msg1.Text = ex.Message; } } /// /// private void btn_rec_Click(object sender, EventArgs e) { try { MessageQueue queue = new MessageQueue(queuestring); queue.Formatter = new BinaryMessageFormatter(); int count = 0; foreach (System.Messaging.Message message in queue) { count++; break; } if (count > 0) { System.Messaging.Message message = queue.Receive(); byte[] buffer = (byte[])message.Body; lbl_msg2.Text = System.Text.Encoding.UTF8.GetString(buffer); } else lbl_msg2.Text = "没有消息!"; } catch (Exception ex) { lbl_msg2.Text = ex.Message; } } /// /// private void btn_send_Click(object sender, EventArgs e) { try { string mss = DateTime.Now.ToString("当前时间:yyyy-MM-dd HH:mm:ss.fff。"); MessageQueue queue = new MessageQueue(queuestring); byte[] msg = System.Text.Encoding.UTF8.GetBytes(mss); System.Messaging.Message Msg = new System.Messaging.Message(msg, new BinaryMessageFormatter()); Msg.AcknowledgeType = AcknowledgeTypes.PositiveReceive | AcknowledgeTypes.PositiveArrival; Msg.Label = "消息" + times; queue.Send(Msg); queue.Close(); lbl_msg3.Text = "已发送!"; times++; } catch (Exception ex) { lbl_msg3.Text = ex.Message; } } } }```