Sign in to follow this  
nixon

Should I use Threads in my C# game?

Recommended Posts

nixon    122
Hi, Im making my first 2-player online turn-based game. Im thinking if I should use threads in my game client: - One thread for networking (always on) - One thread for rendering (goes to sleep when the game window is minimized) Im using the following network library: http://code.google.com/p/lidgren-library-network/ For the Message Loop, I'm using: http://www.drunkenhyena.com/cgi-bin/view_net_article.pl?chapter=2;article=15 The network library uses Thread.Sleep(1) at the end of each network listening call. ----------------------------------------------------------------- If I would do it all in one thread, would this be a good idea? Would you skip this thread.sleep(1) or not? while (Win32.AppStillIdle) { // Network while ((msg = Client.ReadMessage()) != null); HandleMessage(msg); // Updates the Game State // Graphic if(!WindowMinimized) { Render(); } Thread.Sleep(1); // Should I have this line or not?!?!? } Thank you.

Share this post


Link to post
Share on other sites
ApochPiQ    23061
Sleeping at the end of a busy loop is good practice no matter how many threads you run; it's considered poor etiquette to chew up the CPU if you don't need it. Personally, I'd leave it in, although if your game really hauls a lot of resources, you may consider only sleeping/throttling back CPU usage when your game does not have the focus (i.e. some other program is active).

I don't see any particular need to introduce a second thread in your design. In general, my opinion is that it is best to avoid multithreading if it is not absolutely necessary, because it dramatically increases the complexity of a program and makes debugging several times more difficult. Since you haven't run into any particular problems that seem to be solvable only with multithreading, I would say stick with one thread.

Share this post


Link to post
Share on other sites
alun    100
There's no point trying to repaint the screen faster than the refresh rate of the user's monitor. Rather than calling Thread.Sleep(0) ('better' than Thread.Sleep(1) but the difference is marginal) before you render, test that you should actually render now, and sleep if you shouldn't.

That way, if your program really needs 100% of the CPU, it'll get 100% of the CPU. If it doesn't, other programs will get the CPU.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this