I have a game in XNA which needs to do network calls. In the update method I determine what needs to be sent and then add it to a list of stuff to send. Then I run the network call. This slows down the application alot obviously. So I first tried creating a new thread like this in the update to make it do it on a seperate thread:
Thread thread;
thread = new Thread(
new ThreadStart(DoNetworkThing));
thread.Start();
I presume creating threads has overhead etc which results in this being even slower.
Finally, I made a method that has while(true){DoNetworkThing();} in it which will keep looping round and run the network call over and over again(it does check if its already busy with one, and whether there is stuff to send). That method I called in the LoadContent method in a thread, so it will run alongside the game in its own thread.
But that is really slow too.
So what am I doing wrong? What is the best way of doing this?
Thanks
I had this exact problem when initially attempting to use threads on XNA — adding a thread slowed everything down. It turned out that thread affinity was the issue.
On Xbox 360, by default, all threads run on the same processor core; this behaviour differs from Windows, where the kernel places threads onto other cores for you. (See answers on this thread at MSDN social for detail.)
To get around it, you need to set the affinity for your thread to another core in your thread function:
The documentation for
Thread.SetProcessorAffinitystates that on XNA, cores 0 and 2 are reserved for the framework; core 1 and cores 3-5 are free for your use. The main thread (the thread containing yourmain()function) will be on core 1. The code above arbitrarily sets the thread to run on core 3, but you can choose a different core, or add code to programmatically choose a core (which you may want to do if you have more than a few threads).Finally, note the
#ifdefguard –Thread.SetProcessorAffinityis only available on Xbox; it won’t even compile on Windows!