0
votes

I'm trying to create a UDP listener within a Windows form. I want to listen on an address and endpoint and want to display the received text in a textbox on the form. I've tried to attack this from different angles.

One of my attempts is trying to use a BackgroundWorker to allow for the listener code to keep running, while still having control in the UI thread. As the listener keeps listening, I want to keep adding the ascii data that's sent to a multiline text box (using Visual Studio 2010, and C#). I've added a BackgroundWorker to the form, so I can start and stop the listener. I can receive the test from a sender client and display it in a MessageBox, but am having trouble updating the textbox on the form with that same text (which is what I actually want to do).

Another angle I've tried is trying the code from a post here at stack overflow which uses a UdpClient that calls the BeginReceive method with an AsyncCallback. In the example, the callback uses the passed in UdpClient to call the EndReceive method, grab the data, and then print it out using a Console.WriteLine. I tried that code, trying to add the received text to a textbox on the form, but to no avail. Is there a way to display the received text in a textbox on the form using a BackgroundWorkder, or maybe a UdpClient, or should I investigate using a seperate thread for this or possibly some other way. Not having done any multithreaded programs, I'm a bit of a newbie in this regard. Any help would be appreciated. Thanks.

2
Would be much better to have some code to look at than an block of text describing the code. - weston

2 Answers

1
votes

You were probably close with your BackgroundWorker implementation; you just have to insure that the background thread never tries to update the UI. You have to move your code to update the text box to the ProgressChangedEventHandler you attach to the BackgroundWorker. When you receive a message, update a buffer (protected with a lock) and call the ReportProgress method. The ReportProgress method will call the ProgressChangedEventHandler on the UI thread, which can update the text box based on what's in the buffer.

1
votes

The best approach is the async read that you have tried. This essentially does the same thing as using a background worker, but the library does all the work for you.. The tricky bit is that your data received event is called on a worker thread, so to update the UI you need to transfer control back to the ui thread. This can be done by using a 'BeginInvoke' on any UI element (form or control) to execute your update code on the correct thread. If you do a search on this you'll find loads of examples.