Fairly new to programming but need this code to get some hardware I am building working.
I am writing ac# program to connect to a telnet server and read from the feed then display in a text box (sounds simple enough)...
A connect button connects the telnet and runs a backgroundworker that then waits for the telnet session to send data and then outputs to the text box in the complete section of the background worker.
My question is, how then do I get the background worker to run again once that read is received?
If i use a whil loop in the connect button that encapsulates the backgroundworker starter then the ui freezes up (which was the whole point of using a background worker to start with).
THanks for your help.
Shags
You don't say how you're reading from the telnet server.
I wouldn't recommend using a BackgroundWorker
or even a Task
for this. You can have your GUI code create a TcpClient
instance. Once that's created, the button handler calls BeginConnect
, passing a reference to the function that will be called when the connection is made.
When the connection callback is called, it gets the stream (calls GetStream
), and calls BeginRead
on the stream. And the read handler calls BeginRead
again. So what you end up with is an asynchronous loop.
See the examples for BeginConnect and EndConnect , and the NetworkStream
BeginRead and EndRead
methods.
Also, you might get some good information from a search for [TcpClient asynchronous example].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.