发送消息到消息队列 private void button1_Click(object sender, EventArgs e) { string queueName=@"./private$/TestQueue"; if (!MessageQueue.Exists(queueName)) { // Open queue using (System.Messaging.MessageQueue queue = MessageQueue.Create(queueName, false)) { //给访问权限 queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl); // Create message System.Messaging.Message message = new System.Messaging.Message(); message.Body = textBox1.Text.Trim(); message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) }); // Put message into queue queue.Send(message); } } else { //MessageQueue.Delete(queueName); } } 从消息队列取回消息 private void button2_Click(object sender, EventArgs e) { string queueName = @"./private$/TestQueue"; // Open queue System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(queueName); //给访问权限 queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl); // Receive message, 同步的Receive方法阻塞当前执行线程,直到一个message可以得到 System.Messaging.Message message = queue.Receive(); message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) }); textBox2.Text = message.Body.ToString(); MessageQueue.Delete(queueName); } //给访问权限 很重要,没有权限是会报错的 queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);