Click here to Skip to main content
15,793,535 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Background: I am using a special internal website to run pings on internal devices. That is why i am using a website to run the pings instead of just doing it an easier way.

Problem: I am having a problem stopping a streamreader that is reading information streaming from a website. The problem is if i try to stop the reader it won't actually stop until it receives more information from the stream. The streamreader is in a thread as well. Am i missing something obvious to stop the streamreader immediately?

Private Sub DoThreadedPing()
Dim client As New WebClient
Dim strm As Stream
Dim sr As StreamReader
Dim pingTXT As String
    strm = client.OpenRead(New Uri(Ping1Info))
    sr = New StreamReader(strm)
         pingTXT = sr.ReadLine
         If pingTXT IsNot Nothing Then TextBox1.Invoke(New PingDelegate(AddressOf WritePing), pingTXT)
    Loop While pingTXT IsNot Nothing

    Catch ex As Exception

End Sub

*update 1*
The problem seems to lay in the "pingTXT = sr.ReadLine" code. Tried using a BackgroundWorker and it works a little better but still waits until it receives data before cancelling the worker.

Is there a better way to check for data before using the ReadLine command so it only tries to read when there is data and not try to read and wait for data to arrive?

*update 2*
Got it working now using an array of BackgroundWorker's and just tracking which ones are still busy and move to the next Worker until i find one not busy and run the ping on that one. Couldn't get the BeginRead thing to work, i was probably doing something wrong.
Updated 25-Jan-10 15:30pm

Use a BackgroundWorker object instead of a normal thread. They are much easier to work with because you can just call BackgroundWorker.CancelAsync() and be done with it.
Share this answer
You can Asynchronously read the stream, i.e. strm.BeginRead see link[^] for documentation. You could also take a look here[^] for an article on an asynchronous streamreader.
Share this answer
This is just another thought:

Use another module level volatile variable(a boolean variable will serve the purpose) which will denote the status of the thread. Instead of aborting the thread completely you will change the status of variable. The execution has to come out of the loop and finally will be executed.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900