' Cast the state into the event evs = state.ResetEvent
' Set the priority and name Thread.CurrentThread.Priority = ThreadPriority.BelowNormal Try If Not state.ThreadName Is Nothing Then Thread.CurrentThread.Name = state.ThreadName End If Catch e As Exception ' Thread name can only be set once ' Don't set it and get out End Try
'Console.WriteLine("Listen {0} ", state.ThreadName) Try ' Set the path property on the MessageQueue object, assume private in this case objMQ.Path = mstrMachine & "\private$\" & mstrQueue ' Repeat until Interrupt received While True Try ' Sleep in order to catch the interrupt if it has been thrown Thread.CurrentThread.Sleep(100)
' Set the Message object equal to the result from the receive function ' Will block for 1 second if a message is not received objMsg = objMQ.Receive(New TimeSpan(0, 0, 0, 1))
' Message found so signal the event to say we're working evs.Reset() ' Processing the message ProcessMsg(objMsg) ' Done processing
Catch e As ThreadInterruptedException ' Catch the ThreadInterrupt from the main thread and exit Exit While Catch excp As MessageQueueException ' Catch any exceptions thrown in receive ' Probable timeout Finally ' Console.WriteLine("Setting Event " & Thread.CurrentThread.GetHashCode()) ' Done with this iteration of the loop so set the event evs.Set() End Try
' If finished then exit thread If mFinished Then 'console.WriteLine("exiting " & thread.CurrentThread.GetHashCode) Exit While End If
End While
Catch e As ThreadInterruptedException ' Catch the ThreadInterrupt from the main thread and exit End Try
End Sub
Private Sub ProcessMsg(ByVal pMsg As Message) ' Here is where we would process the message End Sub
Public Sub Monitor() Dim intItem As Integer Dim objState As EventState
ReDim mEvs(mWorkItems) mFinished = False
'Console.WriteLine("Queuing {0} items to Thread Pool", mWorkItems)
For intItem = 0 To mWorkItems - 1 'Console.WriteLine("Queue to Thread Pool {0}", intItem) mEvs(intItem) = New ManualResetEvent(False) objState = New EventState(mEvs(intItem), "Worker " & intItem) ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf Me.Listen), _ objState) Next
End Sub
Public Sub Finish(Optional ByVal pTimeout As Integer = 0) 'Console.WriteLine("Waiting for Thread Pool to drain") ' Make sure everyone gets through the last iteration mFinished = True ' Block until all have been set If pTimeout = 0 Then WaitHandle.WaitAll(mEvs) ' Waiting until all threads signal that they are done. Else WaitHandle.WaitAll(mEvs, pTimeout, True) End If 'Console.WriteLine("Thread Pool has been drained (Event fired)") End Sub