Reputation: 4951
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.
Upvotes: 1
Views: 1417
Reputation: 44096
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:
var guiDispatcher = Dispatcher.CurrentDispatcher;
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):
Message msg = myNetworkComms.GetMessage(); // or whatever
Action updateGui = () => myViewModel.ApplyNewMessage(msg);
guiDispatcher.BeginInvoke(DispatcherPriority.Normal, updateGui); // Run updateGui on 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?
Upvotes: 1
Reputation: 900
This might not be the easiest example, but it is a WPF game with mulitple AI's connected by socket https://github.com/bondehagen/CloudWars
I'm using an DispatcherTimer Class to keep the GUI spinning and then check a queue for incoming commands to control the players. This class may be useful https://github.com/bondehagen/CloudWars/blob/master/Simulator/CloudWars.Gui/Helpers/WindowThread.cs
Upvotes: 1