I have a class, which raises an evert to the UI.
the thing is that _conn calls another thread, which wiats for data. When data arrives the above event is raised, but .NET doesn't like adding the data to a treeview as the event has come from another thread.VB Code:
Private Withevents _Conn As MyConnection Private Sub _Conn_Data(ByVal Data As String) Handles _Conn.Data Treeview1.Nodes.Add Data End Sub
To get this to work I must do:
this is not good.VB Code:
Private _Data As String Private Sub _Conn_Data(ByVal Data As String) Handles _Conn.Data _Data = Data Treeview1.Invoke(CType(AddressOf addnewnode, MethodInvoker)) End Sub Private Sub AddNewNode() Treeview1.Nodes.Add _Data End Sub
What I would like is the event to be raised in the correct thread.
Someone mentioned that queues could be used.
The that I use is this:
The function StartAsyncRead is the one that starts a new thread for receiving data.VB Code:
Imports System.Net.Sockets Imports System.IO Imports System.Text Public Class TCPConnection Public Event DataArrived(ByVal Data() As Byte) Public Event Disconnected() Private Const READ_BUFFER_SIZE As Integer = 255 Private _ReadCallBack As AsyncCallback Private _HostAddress As String Private _Port As Integer Private _TCPClient As TcpClient Private _NS As NetworkStream Private _SW As StreamWriter ' Private _SR As StreamReader Private _Buffer(READ_BUFFER_SIZE - 1) As Byte Public Sub New(ByVal HostAddress As String, ByVal Port As Integer) _HostAddress = HostAddress _Port = Port Connect() End Sub Public ReadOnly Property HostAddress() As String Get Return _HostAddress End Get End Property Public ReadOnly Property Port() As Integer Get Return _Port End Get End Property Public Sub Connect() _TCPClient = New TcpClient(_HostAddress, _Port) _NS = _TCPClient.GetStream() '_SR = New StreamReader(_NS, Encoding.ASCII) _SW = New StreamWriter(_NS, Encoding.ASCII) _SW.AutoFlush = True StartAsyncRead() End Sub Public Sub Disconnect() _TCPClient.Close() _TCPClient = Nothing RaiseEvent Disconnected() End Sub Public Sub SendData(ByRef Data As String) _SW.Write(Data) End Sub Private Sub StartAsyncRead() _ReadCallBack = New AsyncCallback(AddressOf DoRead) _NS.BeginRead(_Buffer, 0, READ_BUFFER_SIZE, _ReadCallBack, Nothing) End Sub Private Sub DoRead(ByVal Result As IAsyncResult) Try Dim BytesRead As Integer = _NS.EndRead(Result) If BytesRead < 1 Then Disconnect() Else Dim Data(BytesRead - 1) As Byte _Buffer.Copy(_Buffer, 0, Data, 0, BytesRead) RaiseEvent DataArrived(Data) StartAsyncRead() End If Catch e As Exception Disconnect() End Try End Sub End Class
Woka




Reply With Quote