一、简介
1、这篇文章是在本机中创建消息队列,你可以参考这篇博客,来获取远程消息队列的相关知识。
2、这篇文章没有涉及Process类的详解,下一篇文章将介绍。
c# 消息队列(三)c# 消息队列的Process使用方法: 重点介绍process.StartInfo.Arguments
二、例子
#region 消息队列
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
#region 创建消息队列
const string queueName = @".\Private$\jiyiqin";
MessageQueue mq = null;
if (!MessageQueue.Exists(queueName))// 如果指定的路径queueName中不存在队列,那么在该路径,即queueName中创建一个消息队列。jiyiqin就是你想要创建消息队列的名字
{
mq = MessageQueue.Create(queueName);//创建名称jiyiqin的消息队列的实例。
Console.WriteLine("创建消息队列完成:" + queueName);
}
else //如果消息队列jiyiqin已经存在,那么创建该消息队列的一个实例
{
mq = new MessageQueue(queueName);//创建名称jiyiqin的消息队列的实例。
}
mq.SetPermissions("Administrator", MessageQueueAccessRights.FullControl);
mq.SetPermissions("ANONYMOUS LOGON", MessageQueueAccessRights.FullControl);
mq.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
#endregion
#region 发送消息队列
string strTx = "123我";
Message msgTx = new Message();
msgTx.Body = strTx;
msgTx.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
mq.Send(msgTx);
#endregion
#region 接收消息队列
//接收到的消息对象
Message msgRx = mq.Receive();
//指定格式化程序
msgRx.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
//接收到的内容
string strRx = msgRx.Body.ToString();
System.Windows.Forms.MessageBox.Show(strRx);
#endregion
}
}
}
#endregion