0
當我在我的線程中引發事件時,線程不再在循環中運行。線程中的VB.NET RaiseEvent
Public Sub readStream()
Dim netStream As NetworkStream = Me.client.GetStream()
Do
Try
Dim inStream As Byte() = New Byte(20000) {}
netStream.Read(inStream, 0, CInt(Me.client.ReceiveBufferSize))
Console.WriteLine("Received something")
RaiseEvent rsh(Me, New ReceiveStreamEvent(System.Text.Encoding.ASCII.GetString(inStream)))
Console.WriteLine("I am still alive")
Catch ex As Exception
Console.WriteLine("ReadStream Error: " & ex.Message.ToString())
End Try
Thread.Sleep(100)
Loop
End Sub
你可以看到,「我還活着」永遠不會發生。我的確在C#相同的代碼,我沒有它這個問題。所以當RaiseEvent被調用時,線程將不會繼續。我沒有錯誤,沒有消息。
下面是完整的類:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Net.Sockets
Imports System.Threading
Public Delegate Sub ReceiveStreamHandler(source As Object, e As ReceiveStreamEvent)
Public Class ReceiveStreamEvent
Inherits EventArgs
Private stream As String
Public Sub New(stream As String)
Me.stream = stream
End Sub
Public Function getStream() As String
Return Me.stream
End Function
End Class
Public Class server
Private client As TcpClient
Private readThread As Thread
Public Event rsh As ReceiveStreamHandler
Public Sub New()
Try
Me.client = New TcpClient("172.16.26.56", 8000)
Me.readThread = New Thread(AddressOf readStream)
Me.readThread.Start()
Me.readThread.Priority = ThreadPriority.Highest
Catch ex As Exception
Console.WriteLine("TCP conn error: " & ex.Message.ToString())
End Try
End Sub
Public Sub disconnect()
Try
Me.readThread.Abort()
Me.client.Close()
Catch ex As Exception
Console.WriteLine("TCP disc error: " & ex.Message.ToString())
End Try
End Sub
Public Sub readStream()
Dim netStream As NetworkStream = Me.client.GetStream()
Do
Try
Dim inStream As Byte() = New Byte(20000) {}
netStream.Read(inStream, 0, CInt(Me.client.ReceiveBufferSize))
Console.WriteLine("Received something")
RaiseEvent rsh(Me, New ReceiveStreamEvent(System.Text.Encoding.ASCII.GetString(inStream)))
Console.WriteLine("I am still alive")
Catch ex As Exception
Console.WriteLine("ReadStream Error: " & ex.Message.ToString())
End Try
' Thread.Sleep(100)
Loop
End Sub
Public Sub writeStream(message As String)
Dim netStream As NetworkStream = Me.client.GetStream()
Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes(message)
netStream.Write(outStream, 0, outStream.Length)
netStream.Flush()
End Sub
End Class
確保您的路由器上啓用了端口轉發功能嗎?你有沒有確保該端口不被Windows防火牆阻止。另外,如果你正在處理你從另一個線程提出的事件,你會得到一個非法的crossthread錯誤,我建議在你的服務器中添加一個「Parent As Control」屬性,這樣你可以引發一個私有事件,稍後調用在父線程上引發一個公共事件(父線程可以處理)。 – 2014-10-10 14:32:06