I'm trying to read data from NetworkStream. I write next code:
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim tcpclnt1 As New TcpClient
Dim streamTcp1 As NetworkStream
Dim DataBuffer(1024) As Byte 'Buffer for reading
Dim numberOfBytes As Integer
' event for reading data from stream
Dim evtDataArrival As New AsyncCallback(AddressOf DataProcessing)
Private Sub Btn_Connect5000_Click(sender As Object, e As EventArgs)_
Handles Btn_Connect5000.Click
' Connecting to server
tcpclnt1 = New TcpClient
tcpclnt1.Connect("192.168.1.177", 5000)
streamTcp1 = tcpclnt1.GetStream() 'Create stream for current tcpClient
' HERE WE START TO READ
streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
End Sub
Public Sub DataProcessing(ByVal dr As IAsyncResult)
numberOfBytes = streamTcp1.EndRead(dr) 'END READ
' ...HERE SOME ROUTINE FOR PRINT DATA TO TEXTBOXES...
'START NEW READING
streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
End Sub
Private Sub Btn_Disconnect5000_Click(sender As Object, e As EventArgs)_
Handles Btn_Disconnect5000.Click
' Disconnect from port 5000. Close TcpClient
streamTcp1.Dispose()
streamTcp1.EndRead(Nothing) 'And here mistake appears !!!
streamTcp1.Close()
tcpclnt1.Close()
End Sub
End Class
Problem: I create new client and new stream. By using BeginRead
as I understand it starts to read data in new thread. So to do it for real time data, I start new BeginRead
at the end of DataProcessing
function. But I face the problem when try to disconnect (look at Btn_Disconnect5000_Click
function): I try to close stream and client but it sill try to read in DataProcessing
method and says me:
Cannot access a disposed object
(Thanks to djv for correct translation!).
So I suppose I need to stop thread first but can't figure out how to do this: I tried Dispose()
method, tried close stream first but still can't. Also I tried to call EndRead
method manually, but can't understand what I have to assign to it as argument (parameter).
NetworkStream
instead of callingEndRead
(my answer somewhat explains why you don't need to callEndRead
there either). – Luba