Microsoft Message Queuing (MSMQ) 是 Windows 內建的訊息佇列基礎設施,提供可靠的非同步通訊機制。應用程式可將訊息送入佇列,另一端程式稍後讀取處理,達成解耦、削峰填谷、跨程序/跨機器資料交換。本文涵蓋 Windows 7 安裝 MSMQ、程式碼建立佇列、發送/接收簡單與複雜物件訊息的完整範例。

專案需加入參考:System.Messaging
[Serializable]
public class MsgModel
{
public string Id { get; set; }
public string Content { get; set; }
public MsgModel(string id, string content)
{
Id = id;
Content = content;
}
public override string ToString()
{
return $"Id:{Id}, Content:{Content}";
}
}
using System;
using System.Messaging;
public class MsmqHelper
{
private const string QueuePath = @".\private$\MsgQueue"; // 本機私有佇列
// 確保佇列存在
public static void EnsureQueueExists()
{
if (!MessageQueue.Exists(QueuePath))
{
MessageQueue.Create(QueuePath, true); // true = 交易型佇列
}
}
// 發送簡單字串訊息
public static void SendSimple(string label, string body)
{
EnsureQueueExists();
using (var mq = new MessageQueue(QueuePath))
{
var msg = new Message
{
Label = label,
Body = body,
Formatter = new XmlMessageFormatter(new Type[] { typeof(string) })
};
mq.Send(msg);
}
}
// 接收簡單字串訊息
public static string ReceiveSimple()
{
EnsureQueueExists();
using (var mq = new MessageQueue(QueuePath))
{
mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
if (mq.GetAllMessages().Length > 0)
{
var msg = mq.Receive(TimeSpan.FromSeconds(5));
return msg?.Body?.ToString();
}
}
return null;
}
// 發送複雜物件 (需 Serializable)
public static void SendComplex(string label, T body) where T : class
{
EnsureQueueExists();
using (var mq = new MessageQueue(QueuePath))
{
var msg = new Message
{
Label = label,
Body = body,
Formatter = new XmlMessageFormatter(new Type[] { typeof(T) })
};
mq.Send(msg);
}
}
// 接收複雜物件 (泛型)
public static T ReceiveComplex() where T : class
{
EnsureQueueExists();
using (var mq = new MessageQueue(QueuePath))
{
mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(T) });
if (mq.GetAllMessages().Length > 0)
{
var msg = mq.Receive(TimeSpan.FromSeconds(5));
return msg?.Body as T;
}
}
return null;
}
}
MSMQtest.aspx.cspublic partial class MSMQtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 測試發送與接收複雜物件
MsmqHelper.SendComplex("ComplexMsg", new MsgModel("1", "測試訊息內容"));
var model = MsmqHelper.ReceiveComplex();
if (model != null)
Response.Write($"接收成功: {model}
");
else
Response.Write("佇列無訊息
");
}
}
.\private$\QueueName (本機私有)、MachineName\private$\QueueName (遠端)。XmlMessageFormatter 跨平台相容性佳;BinaryMessageFormatter 效能較好但限 .NET 環境;ActiveXMessageFormatter 相容舊版 COM。true 可支援分散式交易 (DTC),確保訊息處理的原子性。Label 供人工識別,Priority 控制優先順序,Recoverable 確保斷電不遺失。Receive 會封鎖執行緒,生產環境建議使用非同步 BeginReceive 或 Task.Run 配合 CancellationToken。| 現象 | 可能原因 | 解決方向 |
|---|---|---|
| 存取被拒 | 佇列權限不足 | 右鍵佇列 → 內容 → 安全性 → 加入 IIS_IUSRS / 網路服務 完整控制 |
| 序列化失敗 | 型別未標記 Serializable | 類別加上 [Serializable] 或改用 DataContractSerializer |
| 找不到佇列 | 路徑拼寫錯誤或未建立 | 啟動時呼叫 EnsureQueueExists() 自動建立 |
MSMQ 是 Windows 平台上成熟可靠的訊息中介軟體,適合企業內部系統整合、背景作業排程、跨服務非同步通訊。掌握安裝配置、佇列建立、訊息序列化與收發流程,即可在 .NET 應用中輕鬆導入可靠的非同步訊息機制。