1、安裝Message Queue:跨域
在Win7以前,控制面板,添加刪除組件(Windows Message Queue)。服務器
Win7~Win8:控制面板,程序和功能,啓用或關閉Windows功能(找到Windows Message Queue服務器)選項,連同全部子類一併勾上便可,自動安裝。dom
2、使用Message Queue:異步
1)用於各種服務器、計算機之間的通信:async
本地,本身給本身發(直接是.\\Private$\\Queue的私有名字)。spa
遠程計算機:code
FormatName:Direct=TCP:121.0.0.1\\private$\\Queue名字
FormatName:Direct=OS:machinename\\private$\\Queue名字 (僅用於遠程加了域的計算機)。
FormatName:DIRECT=http://222.10.xx.xx/msmq/Private$/Queue名字orm
注意:FormatName必須大小寫徹底按照紅色的寫法!"Direct"能夠隨意。對象
2)默認狀況下,Queue會收到該組所有信息。有時候咱們須要跨域可是指定某臺計算機收到特定信息(好比N臺有1,2,3……N編號的計算機都鏈接到某個服務器Queue,可是不一樣計算機有惟一編號,我發送的信息只發送給特定的計算機編號)。那麼可使用System.Message(使用前必須引用該類庫)的Label,代碼以下(包含收到消息後刪除該信息,防止Queue裏東西愈來愈多):blog
此案例是在我本人計算機上運行,界面上一個「發送」按鈕和2個文本框(分別接受Label爲1和2的消息),防止時間演示過長,使用了異步機制。
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Messaging; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Msg = System.Messaging.Message; namespace MessageQueueDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async Task<string> GetMessage(string labelId) { List<Msg> msgs = new List<Msg>(); //監聽當前本身計算機上的私有隊列 MessageQueue msgQueue = new MessageQueue(@".\private$\myQueue"); string result = null; Random r = new Random(); await Task.Run(() => { //使用該方法容許您動態刪除Queue var me = msgQueue.GetMessageEnumerator2(); Msg tmpMsg = null; for (IEnumerator pointer = me; pointer.MoveNext();) { //先返回當前的Queue tmpMsg = (Msg)pointer.Current; //若是該Label是符合當前文本框能夠接受的Id,刪除該Msg if (tmpMsg.Label == labelId) { tmpMsg = me.RemoveCurrent(); //模擬接收的時間不一樣 Thread.Sleep(r.Next(100, 500)); //必須指定每個Msg的存儲信息格式 tmpMsg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); msgs.Add(tmpMsg); //必須加上去,由於刪除當前的Msg以後不使用「重置」,致使MoveNext爲false。 me.Reset(); } } if (msgs.Count > 0) { result = string.Join(",", (from m in msgs select m.Body.ToString())); } }); return result; } private async void button1_Click(object sender, EventArgs e) { //初始化已經建立的Queue MessageQueue msgQueue = new MessageQueue(@".\private$\myQueue"); //模擬發送Msg(1和2交替發送) for (int i = 1; i < 11; i++) { Msg message = new Msg(i % 2 == 0 ? "1" : "2", new XmlMessageFormatter(new Type[] { typeof(string) }));
//Send第一個參數:發送的消息對象;第二個參數:Label
msgQueue.Send(message, i % 2 == 0 ? "1" : "2");
} //異步接收 var content1 = await GetMessage("1"); var content2 = await GetMessage("2"); textBox2.Text = content1; textBox3.Text = content2; } } }