HOW TO:在 .NET Compact Framework 中使用 MSMQ
更新:2007 年 11 月
建立使用訊息佇列 (MSMQ) 的 .NET Compact Framework 應用程式,與 .NET Framework 中所使用的處理序非常相似。不過,Windows CE 並不支援 .NET Compact Framework 中的 MSMQ 中所描述的所有功能。
下列程式碼範例會示範如何在相同的裝置上建立訊息佇列、傳送訊息給佇列,以及從佇列接收訊息。在此不需要網路連接。一個簡單類別 (Order) 會用來建立訊息佇列的物件。
這些範例會假設裝置上已經安裝訊息佇列。如需取得訊息佇列元件的詳細資訊,請參閱 .NET Compact Framework 中的 MSMQ。
若要定義 Order 類別
將下列類別加入專案。
' This class represents an object that ' is sent to and received from the queue. Public Class Order Dim ID As Integer Dim DTime As DateTime Public Property orderID() As Integer Get Return Me.ID End Get Set(ByVal value As Integer) Me.ID = value End Set End Property Public Property orderTime() As DateTime Get Return Me.DTime End Get Set(ByVal value As DateTime) Me.DTime = value End Set End Property End Class
若要建立訊息佇列
將下列方法加入至表單。
Private Sub CreateQueue() ' Determine whether the queue exists. If Not MessageQueue.Exists(QPath) Then Try ' Create the queue if it does not exist. myQ = MessageQueue.Create(QPath) MessageBox.Show("Queue Created") Catch ex As Exception MessageBox.Show(ex.Message) End Try Else MessageBox.Show("Queue Exists") End If End Sub
若要將訊息傳送至佇列
將下列方法加入至表單。
Private Sub SendMessageToQueue() ' Create a new order and set values. Dim sendOrder As New Order() sendOrder.orderID = 23123 sendOrder.orderTime = DateTime.Now Try myQ.Send(sendOrder) MessageBox.Show("Message Sent") Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub
若要從佇列接收訊息
將下列方法加入至表單。
Private Sub ReceiveMessageFromQueue() ' Connect to the a queue on the device. myQ = New MessageQueue(QPath) ' Set the formatter to indicate the body contains an Order. Dim targetTypes() As Type targetTypes = New Type() {GetType(Order)} myQ.Formatter = New XmlMessageFormatter(targetTypes) Try ' Receive and format the message. Dim myMessage As Message = myQ.Receive() Dim myOrder As Order = CType(myMessage.Body, Order) ' Display message information. MessageBox.Show("Order ID: " & _ myOrder.orderID.ToString() & _ Chr(10) & "Sent: " & myOrder.orderTime.ToString()) Catch m As MessageQueueException ' Handle Message Queuing exceptions. MessageBox.Show(m.Message) Catch e As InvalidOperationException ' Handle invalid serialization format. MessageBox.Show(e.Message) End Try End Sub
若要測試訊息佇列
對表單加入按鈕,將其標籤設定為 [傳送],用此按鈕呼叫 CreateQueue 和 SendMessageToQueue 方法。
對表單加入另一個按鈕,將其標籤設定為 [接收],用此按鈕呼叫 ReceiveMessageFromQueue 方法。
編譯程式碼
此範例需要下列命名空間的參考:
請參閱
工作
概念
.NET Compact Framework 中的 MSMQ