【发布时间】:2021-09-11 02:32:58
【问题描述】:
我有一个单线程应用程序。它应该连接到本地 MSMQ 队列,一旦收到消息,它应该在继续侦听其他消息之前对其进行处理。这些消息包含应该插入到数据库表中的数据。但是在插入数据之前,它会查询该项目是否已经存在。但是,我认为通过为 ReceiveCompleted 创建一个处理程序,如果队列中有多个消息,则会产生多个线程。那会发生吗?如果是这样,则两条消息中都可能存在重复数据,并且我的 sql 查询可能看不到任何重复,因为第二个线程仍在工作并且尚未将其数据插入数据库表中。
Dim objQueue As New MessageQueue(ConfigurationManager.AppSettings("myQueuePath"))
AddHandler objQueue.ReceiveCompleted, AddressOf QueueReceived
objQueue.BeginReceive()
Private Sub QueueReceived(source As Object, asyncResult As ReceiveCompletedEventArgs)
Dim mq = DirectCast(source, MessageQueue)
Dim objMessage As Message = Nothing
Try
mq.Formatter = New XmlMessageFormatter(New [String]() {"System.String,mscorlib"})
objMessage = mq.EndReceive(asyncResult.AsyncResult)
Dim strMessage As String = objMessage.Body.ToString()
'Call routine to read data, check for suplicates and then insert into database
ProcessBXRS(objMessage)
Catch ex As Exception
'Do some exception handling
End Try
'Listen for next message
mq.BeginReceive()
End Sub
【问题讨论】:
-
没有。您必须再次调用 BeginReceive() 才能触发下一条消息的事件。你总是把它放在事件处理程序的末尾,以确保没有重叠。