在 .NET Framework 2.0 中异步使用消息队列






2.91/5 (4投票s)
提供对消息队列服务器上队列的访问。我们将看到如何异步访问它。
引言
我的第一篇关于消息队列的文章:“在 .NET Framework 2.0 中使用消息队列” 可以帮助你从 Windows 操作系统的消息队列服务器发送和接收消息。现在这里有一件事你可能不知道,当消息队列服务器中有消息时。
你不能一直调用简单的接收命令或窥视命令来检查队列中是否有任何消息可用。如果你这样做,你会发现应用程序会一直挂起,直到找到队列中的任何消息为止。因此,为了解决这个问题,我们可以异步使用此消息队列。为此,我们需要更改接收消息的方法。
我们将使用 BeginPeek
来开始窥视消息队列,以查看是否有任何新消息到达,并使用 BeginRecieve
来开始从队列接收任何新消息。这种方法在其他线程上工作,这意味着检查和接收消息的工作是在后台完成的。
当我们使用
BeginPeek
方法时,每当找到消息时都会触发一个事件,即PeekCompleted
,它发生在读取消息但不将其从队列中移除时。这是异步操作的结果。BeginRecieve
方法,每当收到消息时都会触发一个事件,即ReceiveCompleted
,它发生在消息已被从队列中移除时。此事件由异步操作引发。
Using the Code
BeginPeek 方法
''create an instance of the messagequeue class as i did in my ealier ariticle
''call the beginpeek method
''this method can be called anytime at formload or on a button event
myQueue.BeginPeek()
一旦调用了 BeginPeek
方法,就会启动一个新线程来检查队列中是否有任何消息。现在我们需要处理 PeekCompleted
事件
'' a sub to handle the event
Private Sub CheckQueueu(ByVal sender As System.Object, _
ByVal e As System.Messaging.PeekCompletedEventArgs) _
Handles myQueue.PeekCompleted
If e.Message.Label = "Example" Then
'' Store the message in the queue for processing
'' i am storing in a Queue
msgQueue.Enqueue(e.Message)
'' remove the message from the queue if its matches
myQueue.Receive()
'' refresh the Queue
myQueue.Refresh
'' Begin a new Peek method
'' this is to restart the BeginPeek asynchnorously
myQueue.BeginPeek()
End If
End Sub
BeginReceive 方法
''create an instance of the messagequeue class as i did in my ealier ariticle
''call the beginpeek method
''this method can be called anytime at formload or on a button event
myQueue.BeginReceive()
一旦调用了 BeginReceive
方法,就会启动一个新线程来检查队列中是否有任何消息。现在我们需要处理 ReceiveCompleted
事件。
'' a sub to handle the event
Private Sub RecQueueu(ByVal sender As System.Object, _
ByVal e As System.Messaging.ReceiveCompletedEventArgs) _
Handles myQueue.ReceiveCompleted
'' Store the message in the queue for processing
'' i am storing in a Queue
msgQueue.Enqueue(e.Message)
'' remove the message from the queue if its matches
myQueue.Receive()
'' refresh the Queue
myQueue.Refresh
'' Begin a new Revceive method
'' this is to restart the BeginReceive asynchnorously
myQueue.BeginReceive()
End If
End Sub
上面的代码是通过研究以及结合文章和示例获得的。在我的下一篇文章中,我将尝试更详细地解释 BeginPeek
和 BeginReceive
方法,以及向它们传递一些参数。
希望这能在某种程度上帮助你。