入门级指南:C#中的队列与MSMQ消息队列的基本操作
首先我们知道队列是先进先出的机制,所以在处理并发是个不错的选择。然后就写两个队列的简单应用。
Queue
命名空间
命名空间:System.Collections,不在这里做过多的理论解释,这个东西非常的好理解。
可以看下官方文档:https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.queue?view=netframework-4.7.2
示例代码
我这里就是为了方便记忆做了一个基本的例子,首先创建了QueueTest类:
包含了获取队列的数量,入队和出队的实现
1 public class QueueTest 2 { 3 public static Queue<string> q = new Queue<string>(); 4 5 #region 获取队列数量 6 public int GetCount() 7 { 8 9 return q.Count; 10 } 11 #endregion 12 13 #region 队列添加数据 14 public void IntoData(string qStr) 15 { 16 string threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); 17 q.Enqueue(qStr); 18 Console.WriteLine($"队列添加数据: {qStr};当前线程id:{threadId}"); 19 } 20 #endregion 21 22 #region 队列输出数据 23 24 public string OutData() 25 { 26 string threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); 27 string str = q.Dequeue(); 28 Console.WriteLine($"队列输出数据: {str};当前线程id:{threadId}"); 29 return str; 30 } 31 #endregion 32 33 }
为了模拟并发情况下也不会出现重复读取和插入混乱的问题所以写了TaskTest类里面开辟了两个异步线程进行插入和读取:
这里只是证明了多线程插入不会造成丢失。无忧证明并发的先进先出
1 class TaskTest 2 { 3 4 #region 队列的操作模拟 5 public static void QueueMian() 6 { 7 QueueA(); 8 QueueB(); 9 } 10 private static async void QueueA() 11 { 12 QueueTest queue = new QueueTest(); 13 var task = Task.Run(() => 14 { 15 for (int i = 0; i < 20; i++) 16 { 17 queue.IntoData("QueueA" + i); 18 } 19 }); 20 await task; 21 Console.WriteLine("QueueAA插入完成,进行输出:"); 22 23 while (queue.GetCount() > 0) 24 { 25 queue.OutData(); 26 } 27 } 28 29 private static async void QueueB() 30 { 31 QueueTest queue = new QueueTest(); 32 var task = Task.Run(() => 33 { 34 for (int i = 0; i < 20; i++) 35 { 36 queue.IntoData("QueueB" + i); 37 } 38 }); 39 await task; 40 Console.WriteLine("QueueB插入完成,进行输出:"); 41 42 while (queue.GetCount() > 0) 43 { 44 queue.OutData(); 45 } 46 } 47 #endregion 48 49 }
效果展示
然后在main函数直接调用即可:
通过上面的截图可以看出插入线程是无先后的。
这张图也是线程无先后。
补充:通过园友的提问,我发现我一开始测试的不太仔细,只注意多线程下的插入,没有注意到输出其实不是跟插入的顺序一致,对不起,这说明queue不是线程安全的,所以这个就当是入队,出队的基础例子并不能说明并发。后面有一个补充的ConcurrentQueue队列是说明了并发线程的先进先出。
MSMQ
msmq是微软提供的消息队列,本来在windows系统中就存在,但是默认没有开启。需要开启。
开启安装
打开控制面板=>程序和功能=> 启动或关闭windows功能 => Microsoft Message Queue(MSMQ)服务器=>Microsoft Message Queue(MSMQ)服务器核心
一般选择:MSMQ Active Directory域服务继承和MSMQ HTTP支持即可。
点击确定等待安装成功。
命名空间
需要引用System.Messaging.DLL
命名空间:System.Messaging
官方资料文档:https://docs.microsoft.com/zh-cn/dotnet/api/system.messaging.messagequeue?view=netframework-4.7.2
示例代码
与上面queue同样的示例方式,创建一个MSMQ类,实现创建消息队列,查询数据,入列,出列功能:
1 /// <summary> 2 /// MSMQ消息队列 3 /// </summary> 4 class MSMQ 5 { 6 static string path = ".\\Private$\\myQueue"; 7 static MessageQueue queue; 8 public static void Createqueue(string queuePath) 9 { 10 try 11 { 12 if (MessageQueue.Exists(queuePath)) 13 { 14 Console.WriteLine("消息队列已经存在"); 15 //获取这个消息队列 16 queue = new MessageQueue(queuePath); 17 } 18 else 19 { 20 //不存在,就创建一个新的,并获取这个消息队列对象 21 queue = MessageQueue.Create(queuePath); 22 path = queuePath; 23 } 24 } 25 catch (Exception e) 26 { 27 Console.WriteLine(e.Message); 28 } 29 30 } 31 32 33 #region 获取消息队列的数量 34 public static int GetMessageCount() 35 { 36 try 37 { 38 if (queue != null) 39 { 40 int count = queue.GetAllMessages().Length; 41 Console.WriteLine($"消息队列数量:{count}"); 42 return count; 43 } 44 else 45 { 46 return 0; 47 } 48 } 49 catch (MessageQueueException e) 50 { 51 52 Console.WriteLine(e.Message); 53 return 0; 54 } 55 56 57 } 58 #endregion 59 60 #region 发送消息到队列 61 public static void SendMessage(string qStr) 62 { 63 try 64 { 65 //连接到本地队列 66 67 MessageQueue myQueue = new MessageQueue(path); 68 69 //MessageQueue myQueue = new MessageQueue("FormatName:Direct=TCP:192.168.12.79//Private$//myQueue1"); 70 71 //MessageQueue rmQ = new MessageQueue("FormatName:Direct=TCP:121.0.0.1//private$//queue");--远程格式 72 73 Message myMessage = new Message(); 74 75 myMessage.Body = qStr; 76 77 myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); 78 79 //发生消息到队列中 80 81 myQueue.Send(myMessage); 82 83 string threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); 84 Console.WriteLine($"消息发送成功: {qStr};当前线程id:{threadId}"); 85 } 86 catch (MessageQueueException e) 87 { 88 Console.WriteLine(e.Message); 89 } 90 } 91 #endregion 92 93 #region 连接消息队列读取消息 94 public static void ReceiveMessage() 95 { 96 MessageQueue myQueue = new MessageQueue(path); 97 98 99 myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); 100 101 try 102 103 { 104 105 //从队列中接收消息 106 107 Message myMessage = myQueue.Receive(new TimeSpan(10));// myQueue.Peek();--接收后不消息从队列中移除 108 myQueue.Close(); 109 110 string context = myMessage.Body.ToString(); 111 string threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); 112 Console.WriteLine($"--------------------------消息内容: {context};当前线程id:{threadId}"); 113 114 } 115 116 catch (System.Messaging.MessageQueueException e) 117 118 { 119 120 Console.WriteLine(e.Message); 121 122 } 123 124 catch (InvalidCastException e) 125 126 { 127 128 Console.WriteLine(e.Message); 129 130 } 131 132 } 133 #endregion 134 }
这里说明一下path这个字段,这是消息队列的文件位置和队列名称,我这里写的“.”(点)就是代表的位置MachineName字段,,代表本机的意思
然后TaskTest类修改成这个样子:
1 class TaskTest 2 { 3 4 #region 消息队列的操作模拟 5 public static void MSMQMian() 6 { 7 MSMQ.Createqueue(".\\Private$\\myQueue"); 8 MSMQA(); 9 MSMQB(); 10 Console.WriteLine("MSMQ结束"); 11 } 12 private static async void MSMQA() 13 { 14 var task = Task.Run(() => 15 { 16 for (int i = 0; i < 20; i++) 17 { 18 MSMQ.SendMessage("MSMQA" + i); 19 } 20 }); 21 await task; 22 Console.WriteLine("MSMQA发送完成,进行读取:"); 23 24 while (MSMQ.GetMessageCount() > 0) 25 { 26 MSMQ.ReceiveMessage(); 27 } 28 } 29 30 private static async void MSMQB() 31 { 32 var task = Task.Run(() => 33 { 34 for (int i = 0; i < 20; i++) 35 { 36 MSMQ.SendMessage("MSMQB" + i); 37 } 38 }); 39 await task; 40 Console.WriteLine("MSMQB发送完成,进行读取:"); 41 42 while (MSMQ.GetMessageCount() > 0) 43 { 44 MSMQ.ReceiveMessage(); 45 } 46 } 47 #endregion
效果展示
本机查看消息队列
创建成功的消息队列我们可以在电脑上查看:我的电脑=>管理 =>计算机管理 =>服务与应用程序 =>消息队列 =>专用队列就看到我刚才创建的消息队列
补充感谢
感谢 virtual1988 提出的queue不是线程安全这个问题,是我没搞清楚。线程安全要使用ConcurrentQueue队列。
谢谢提出的宝贵意见。
ConcurrentQueue
所以我有修改了一下写了个ConcurrentQueue队列的:
修改代码如下:
//public static Queue<string> q = new Queue<string>(); public static ConcurrentQueue<string> q = new ConcurrentQueue<string>(); //public static Queue q =Queue.Synchronized(new Queue()); #region 获取队列数量 public static int GetCount() { return q.Count; } #endregion #region 队列添加数据 public static void IntoData(string qStr) { string threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); q.Enqueue(qStr); System.Threading.Thread.Sleep(10); Console.WriteLine($"队列添加数据: {qStr};当前线程id:{threadId}"); } #endregion #region 队列输出数据 public static string OutData2() { string threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); foreach (var item in q) { Console.WriteLine($"------队列输出数据: {item};当前线程id:{threadId}"); string d=""; q.TryDequeue( out d); } return "211"; } #endregion
task类:
#region 队列的操作模拟 public static async void QueueMian() { QueueA(); QueueB(); } private static async void QueueA() { var task = Task.Run(() => { for (int i = 0; i < 20; i++) { QueueTest.IntoData("QueueA" + i); } }); await task; Console.WriteLine("QueueA插入完成,进行输出:"); } private static async void QueueB() { var task = Task.Run(() => { for (int i = 0; i < 20; i++) { QueueTest.IntoData("QueueB" + i); } }); await task; Console.WriteLine("QueueB插入完成,进行输出:"); } public static void QueueC() { Console.WriteLine("Queue插入完成,进行输出:"); while (QueueTest.GetCount() > 0) { QueueTest.OutData2(); } } #endregion
Main函数调用:
static void Main(string[] args) { try { Stopwatch stopWatch = new Stopwatch(); TaskTest.QueueMian(); Console.ReadLine(); TaskTest.QueueC(); Console.ReadLine(); } catch (Exception e) { throw; } }
插入效果:
输出效果:
推荐阅读
-
深入解析C#中的MSMQ消息队列
-
入门级指南:C#中的队列与MSMQ消息队列的基本操作
-
入门指南:C# 中的队列类型,包括 ConcurrentQueue 和 MSMQ 的基本用法
-
windows下进程间通信的(13种方法)-摘 要 本文讨论了进程间通信与应用程序间通信的含义及相应的实现技术,并对这些技术的原理、特性等进行了深入的分析和比较。 ---- 关键词 信号 管道 消息队列 共享存储段 信号灯 远程过程调用 Socket套接字 MQSeries 1 引言 ---- 进程间通信的主要目的是实现同一计算机系统内部的相互协作的进程之间的数据共享与信息交换,由于这些进程处于同一软件和硬件环境下,利用操作系统提供的的编程接口,用户可以方便地在程序中实现这种通信;应用程序间通信的主要目的是实现不同计算机系统中的相互协作的应用程序之间的数据共享与信息交换,由于应用程序分别运行在不同计算机系统中,它们之间要通过网络之间的协议才能实现数据共享与信息交换。进程间通信和应用程序间通信及相应的实现技术有许多相同之处,也各有自己的特色。即使是同一类型的通信也有多种的实现方法,以适应不同情况的需要。 ---- 为了充分认识和掌握这两种通信及相应的实现技术,本文将就以下几个方面对这两种通信进行深入的讨论:问题的由来、解决问题的策略和方法、每种方法的工作原理和实现、每种实现方法的特点和适用的范围等。 2 进程间的通信及其实现技术 ---- 用户提交给计算机的任务最终都是通过一个个的进程来完成的。在一组并发进程中的任何两个进程之间,如果都不存在公共变量,则称该组进程为不相交的。在不相交的进程组中,每个进程都独立于其它进程,它的运行环境与顺序程序一样,而且它的运行环境也不为别的进程所改变。运行的结果是确定的,不会发生与时间相关的错误。 ---- 但是,在实际中,并发进程的各个进程之间并不是完全互相独立的,它们之间往往存在着相互制约的关系。进程之间的相互制约关系表现为两种方式: ---- (1) 间接相互制约:共享CPU ---- (2) 直接相互制约:竞争和协作 ---- 竞争——进程对共享资源的竞争。为保证进程互斥地访问共享资源,各进程必须互斥地进入各自的临界段。 ---- 协作——进程之间交换数据。为完成一个共同任务而同时运行的一组进程称为同组进程,它们之间必须交换数据,以达到协作完成任务的目的,交换数据可以通知对方可以做某事或者委托对方做某事。 ---- 共享CPU问题由操作系统的进程调度来实现,进程间的竞争和协作由进程间的通信来完成。进程间的通信一般由操作系统提供编程接口,由程序员在程序中实现。UNIX在这个方面可以说最具特色,它提供了一整套进程间的数据共享与信息交换的处理方法——进程通信机制(IPC)。因此,我们就以UNIX为例来分析进程间通信的各种实现技术。 ---- 在UNIX中,文件(File)、信号(Signal)、无名管道(Unnamed Pipes)、有名管道(FIFOs)是传统IPC功能;新的IPC功能包括消息队列(Message queues)、共享存储段(Shared memory segment)和信号灯(Semapores)。 ---- (1) 信号 ---- 信号机制是UNIX为进程中断处理而设置的。它只是一组预定义的值,因此不能用于信息交换,仅用于进程中断控制。例如在发生浮点错、非法内存访问、执行无效指令、某些按键(如ctrl-c、del等)等都会产生一个信号,操作系统就会调用有关的系统调用或用户定义的处理过程来处理。 ---- 信号处理的系统调用是signal,调用形式是: ---- signal(signalno,action) ---- 其中,signalno是规定信号编号的值,action指明当特定的信号发生时所执行的动作。 ---- (2) 无名管道和有名管道 ---- 无名管道实际上是内存中的一个临时存储区,它由系统安全控制,并且独立于创建它的进程的内存区。管道对数据采用先进先出方式管理,并严格按顺序操作,例如不能对管道进行搜索,管道中的信息只能读一次。 ---- 无名管道只能用于两个相互协作的进程之间的通信,并且访问无名管道的进程必须有共同的祖先。 ---- 系统提供了许多标准管道库函数,如: pipe——打开一个可以读写的管道; close——关闭相应的管道; read——从管道中读取字符; write——向管道中写入字符; ---- 有名管道的操作和无名管道类似,不同的地方在于使用有名管道的进程不需要具有共同的祖先,其它进程,只要知道该管道的名字,就可以访问它。管道非常适合进程之间快速交换信息。 ---- (3) 消息队列(MQ) ---- 消息队列是内存中独立于生成它的进程的一段存储区,一旦创建消息队列,任何进程,只要具有正确的的访问权限,都可以访问消息队列,消息队列非常适合于在进程间交换短信息。 ---- 消息队列的每条消息由类型编号来分类,这样接收进程可以选择读取特定的消息类型——这一点与管道不同。消息队列在创建后将一直存在,直到使用msgctl系统调用或iqcrm -q命令删除它为止。 ---- 系统提供了许多有关创建、使用和管理消息队列的系统调用,如: ---- int msgget(key,flag)——创建一个具有flag权限的MQ及其相应的结构,并返回一个唯一的正整数msqid(MQ的标识符); ---- int msgsnd(msqid,msgp,msgsz,msgtyp,flag)——向队列中发送信息; ---- int msgrcv(msqid,cmd,buf)——从队列中接收信息; ---- int msgctl(msqid,cmd,buf)——对MQ的控制操作; ---- (4) 共享存储段(SM) ---- 共享存储段是主存的一部分,它由一个或多个独立的进程共享。各进程的数据段与共享存储段相关联,对每个进程来说,共享存储段有不同的虚拟地址。系统提供的有关SM的系统调用有: ---- int shmget(key,size,flag)——创建大小为size的SM段,其相应的数据结构名为key,并返回共享内存区的标识符shmid; ---- char shmat(shmid,address,flag)——将当前进程数据段的地址赋给shmget所返回的名为shmid的SM段; ---- int shmdr(address)——从进程地址空间删除SM段; ---- int shmctl (shmid,cmd,buf)——对SM的控制操作; ---- SM的大小只受主存限制,SM段的访问及进程间的信息交换可以通过同步读写来完成。同步通常由信号灯来实现。SM非常适合进程之间大量数据的共享。 ---- (5) 信号灯 ---- 在UNIX中,信号灯是一组进程共享的数据结构,当几个进程竞争同一资源时(文件、共享内存或消息队列等),它们的操作便由信号灯来同步,以防止互相干扰。 ---- 信号灯保证了某一时刻只有一个进程访问某一临界资源,所有请求该资源的其它进程都将被挂起,一旦该资源得到释放,系统才允许其它进程访问该资源。信号灯通常配对使用,以便实现资源的加锁和解锁。 ---- 进程间通信的实现技术的特点是:操作系统提供实现机制和编程接口,由用户在程序中实现,保证进程间可以进行快速的信息交换和大量数据的共享。但是,上述方式主要适合在同一台计算机系统内部的进程之间的通信。 3 应用程序间的通信及其实现技术 ---- 同进程之间的相互制约一样,不同的应用程序之间也存在竞争和协作的关系。UNIX操作系统也提供一些可用于应用程序之间实现数据共享与信息交换的编程接口,程序员可以通过自己编程来实现。如远程过程调用和基于TCP/IP协议的套接字(Socket)编程。但是,相对普通程序员来说,它们涉及的技术比较深,编程也比较复杂,实现起来困难较大。 ---- 于是,一种新的技术应运而生——通过将有关通信的细节完全掩盖在某个独立软件内部,即底层的通讯工作和相应的维护管理工作由该软件内部来实现,用户只需要将通信任务提交给该软件去完成,而不必理会它的具体工作过程——这就是所谓的中间件技术。 ---- 我们在这里分别讨论这三种常用的应用程序间通信的实现技术——远程过程调用、会话编程技术和MQSeries消息队列技术。其中远程过程调用和会话编程属于比较低级的方式,程序员参与的程度较深,而MQSeries消息队列则属于比较高级的方式,即中间件方式,程序员参与的程度较浅。 ---- 4.1 远程过程调用(RPC)