I am trying to build a simple LAN chat in c# using WPF as a GUI. Since I want to enable server-less chatting, I’d like for each instance of the application to listen at an IP for multicasted messages and send multicasts to that IP as well. However, all the various tutorials for threaded networking I find on the net use the console, not WPF, which is set in its own thread. I have tried adapting those tutorials, but there is always something failing, such as the GUI thread suspending, or the messages not being processed/added to the GUI. Tutorials about consumer/producer threading systems would be great as well.
Share
There’s nothing different between your scenario and any other scenario with interthread communication except that you’ve got a lot of free work that you can take advantage of b/c you’re marshalling between between WPF and some other thread.
Short version:
When you receive a message from another client in your local stack and you need to let WPF know, use Dispatcher.Invoke from the networking thread to marshal a call to the WPF thread, presumably passing it some kind of Message object. This is extra easy with lambdas:
First, store a reference to the WPF dispatcher on your background thread during app initialization. This is easy because (assuming you aren’t pathologically multithreaded) your WPF thread is the one that’s spinning up your network thread:
Once your other thread is able to access the gui dispatcher, it can asynchronously run code on that dispatcher’s context (in our case, the WPF GUI thread):
All that said, why are you spinning up a separate thread for your network I/O? It seems awfully wasteful of resources. Are you sure there aren’t any async network I/O methods you can take advantage of?