How to abort a thread which is reading from a networkstream?

djdagobert

New member
Joined
Jul 28, 2005
Messages
2
Programming Experience
5-10
Hi,
I've the following problem:
I've a main thread, that creates another thread that has an open connection and is waiting for a response. (In particular: is waiting for a string with a newline at the end)

While this thread is waiting for that line, I want to kill that thread from the main-thread, but the waiting thread will not terminate. WHY?

Here is my code:
VB.NET:
Dim myThread As New Thread(AddressOf connect())
myThread.Start()

Private Sub MIT_Config_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MIT_Config.Click
  myThread.Abort()
  myThread.Join()
End Sub

Private Sub connect()
  Dim client As Net.Sockets.TcpClient
  Try
    client.Connect(server, port)
    Dim myStreamReader As New IO.StreamReader(client.GetStream())
    Dim myStreamWriter As New IO.StreamWriter(client.GetStream())
    Dim line As String
    While True
      line = myStreamReader.ReadLine()
    End While
  Catch e As ThreadAbortException
    MsgBox("Thread wurde abgebrochen:" & Chr(13) & Chr(10) & e.ToString(), MsgBoxStyle.Information, "Information")
  Catch e As Exception
    MsgBox("Error in Connecting to Server:" & Chr(13) & Chr(10) & e.ToString(), MsgBoxStyle.Information, "Error")
  Finally
    client.Close()
  End Try
End Sub
 
Hi ,

Assign a Name to the Thread by like mythread.Name = "my thread"

While Calling Abort use Thread.CurrentThread.Abort() to Abort the Thread.

Here By the Name Property you can check which thread you are Aborting Like

VB.NET:
If Thread.CurrentThread.Name="my Thread" Then 
     Thread.CurrentThread.Abort()
End If
[Code]
 
Hi ,

One more thing when you Abort the thread it calls Exception, so handle the ThreadAbortException where you Abort the Thread


Thanks
Jay
 
Hi,
hmmm I think, I din't get what you mean with:
programmerskills said:
While Calling Abort use
VB.NET:
Thread.CurrentThread.Abort()
to Abort the Thread.
I'm trying to Abort the blocked thread (which is waiting for some Data in myStreamReader.ReadLine()) from the main-program.
But the tread still waits for some data :(
And the expected "ThreadAbortException" will not raise :(

So how can I stop the myStreamReader.ReadLine() from waiting for data?

Greetz
Patrick
 
Hi,


Hmm , i too tried it but it is blocked for Response hence not abortign at the Instance.

See if you can set
client.ReceiveTimeout = ' Some time out Duration

if you set some time out it will be blocked only for specified seconds.

See if this helps you , I think need to find a different way out :)

Thanks
Jay
 
Back
Top