Threading in XNA

I have an XNA game that needs to make network calls. In the update method, I determine what needs to be sent, and then add it to the list of sent materials. Then I launch a network call. This noticeably slows down the application. So I first tried to create a new thread like this in the update, to do this in a separate thread:

Thread thread; 
thread = new Thread(
new ThreadStart(DoNetworkThing));
thread.Start();

I assume thread creation has overhead, etc., which leads to even slower. Finally, I created a method that has while(true){DoNetworkThing();}one that will continue the loop and start the network call again and again (it checks whether it is already busy alone, and if there is material to send). I called this method in the LoadContent method in the stream, so it will run next to the game in its stream. But it is also very slow.

So what am I doing wrong? What is the best way to do this? Thanks

+3
source share
3 answers

I had this exact problem when I originally tried to use streams in XNA - adding a stream slowed everything down. It turned out that the problem with the thread is related to the problem.

Xbox 360 ; Windows, ​​ . (. MSDN .)

, :

void DoNetworkThing()
{
#ifdef XBOX
    Thread.SetProcessorAffinity(3); // see note below
#endif
    /* your code goes here */
}

Thread thread = new Thread(
 new ThreadStart(DoNetworkThing));
thread.Start();

Thread.SetProcessorAffinity , XNA 0 2 ; 1 3-5 . (, main()) 1. 3, ​​ ( , ).

, , #ifdef guard - Thread.SetProcessorAffinity Xbox; Windows!

+13

, , , , ( )... , ( ), .

:

Thread thread; 
thread = new Thread(new ThreadStart(DoNetworkThing));

// you should set the thread to background, unless you 
// want it to live on even after your application closes
thread.IsBackground = true;
thread.Start();

, DoNetworkThing :

void DoNetworkThing()
{
    while(someConditionIsTrue)
    {
        // do the networking stuff here
    }
}

, - :

Thread thread = new Thread(()=>
   {
       while(true)
       {
           DoNetworkThing();
       }
   });
thread.IsBackground = true;
thread.Start();

, - DoNetworkingThing. :

void DoNetworkThing()
{
    // do the networking thing, but note
    // that this time your infinite while
    // loop is outside the function
}

, , , . , :

  • , .
  • , , .

, , STRONGLY , , . , , .

Joe Duffy Windows, #.

+1

It might be worth checking to see if performance improves ThreadPool. Creating many threads can be expensive.

http://msdn.microsoft.com/en-us/library/h4732ks0(v=vs.100).aspx

0
source

Source: https://habr.com/ru/post/1752735/


All Articles