我已經寫以下代碼以執行某些併發HTTP發佈和文件歸檔:通過HTTP這是線程代碼做我認爲是什麼?
Dim t1 As New Threading.Thread(New Threading.ThreadStart(AddressOf ProcessNTSMessageQueue))
Dim t2 As New Threading.Thread(New Threading.ThreadStart(AddressOf ProcessNTSMessageQueue))
Dim t3 As New Threading.Thread(New Threading.ThreadStart(AddressOf ProcessSuccessfulNTSMessageQueue))
t1.Start()
t2.Start()
t3.Start()
t1.Join()
t2.Join()
t3.Join()
我有兩個線程(1 & 2)讀取XML的消息的隊列和張貼消息發送到web服務器。一旦發佈消息,它將從此隊列中出列,並添加到第二個隊列中。線程3讀取該隊列,並簡單地將XML寫入文件。
我期望看到XML文件逐漸顯示爲處理消息隊列(有時消息隊列可能需要大約40分鐘才能處理)。我實際看到的是沒有XML文件出現。我是我誤解了代碼?
*編輯。以下是四種相關線程方法的代碼:
Private Sub ProcessNTSMessageQueue()
While True
Dim msg As String = Nothing
SyncLock _MessageQueue
If _MessageQueue.Count > 0 Then
msg = _MessageQueue.Dequeue()
Else
Exit Sub
End If
End SyncLock
'Post the message
'it's important to do this outside lock()
If msg <> Nothing Then
Me.PostXMLToNTS(msg)
End If
End While
End Sub
Private Sub ProcessSuccessfulNTSMessageQueue()
While True
Dim msg As String = Nothing
SyncLock _SentMessageQueue
If _SentMessageQueue.Count > 0 Then
msg = _SentMessageQueue.Dequeue()
Else
Exit Sub
End If
End SyncLock
'Post the message
'it's important to do this outside lock()
If msg <> Nothing Then
Me.ArchiveXMLAsFile(Guid.NewGuid.ToString, msg)
_SuccessfulMessageCount += 1
End If
End While
End Sub
Private Function PostXMLToNTS(ByVal XMLString As String) As Boolean
Try
Dim result As Net.HttpStatusCode = NTSPoster.PostXml(XMLString, _Settings.NTSPostURLCurrent, _Settings.NTSPostUsernameCurrent, _Settings.NTSPostPasswordCurrent)
Select Case result
Case Net.HttpStatusCode.Accepted, Net.HttpStatusCode.OK 'Good
If _SentMessageQueue Is Nothing Then
_SentMessageQueue = New Queue(Of String)
End If
_SentMessageQueue.Enqueue(XMLString)
Return True
Case Else 'Probably bad
If _FailedMessageQueue Is Nothing Then
_FailedMessageQueue = New Queue(Of String)
End If
_FailedMessageQueue.Enqueue(XMLString)
Return False
End Select
Catch ex As Exception
Throw
End Try
End Function
Private Sub ArchiveXMLAsFile(ByVal name As String, ByVal XML As String)
Try
'Create directory in archive location based on todays date
Dim dir As New DirectoryInfo(Me.TodaysXMLArchiveLocation)
'If the directory does not already exist then create it
If Not dir.Exists Then
dir.Create()
End If
Dim FileName As String = String.Format("{0}.xml", name)
Using sw As StreamWriter = New StreamWriter(Path.Combine(dir.FullName, FileName))
sw.Write(XML)
sw.Close()
End Using
Catch ex As Exception
Throw
End Try
End Sub
您將需要顯示「ProcessNTSMessageQueue」和「ProcessSuccessfulNTSMessageQueue」函數的代碼。 – 2009-11-18 15:31:38
感謝大家的幫助,這是我第一次進入線程,我不確定我在這個階段做了什麼! – Simon 2009-11-20 13:42:21