Click here to Skip to main content
15,885,998 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
*edit* so this wasn't causing my game to be sluggish, something else was. But still, I would like to know if there is a better way of using this thread to be efficient.


My thread is supposed to read information sent by a server, and the information could come at any point in time. Right now I believe this thread is eating up too much cpu usage and is causing my game to be sluggish. Does anyone know how I can reduce the resources needed for this thread?
I understand that the while loop is basically going off without downtime, so it's throwing cpu out the window :( After googling a whole bunch of stuff that I'm not completely sure how to use properly, I'm stuck.


C#
static public void Listener()   //thread
        {
            networkStream = socketForServer.GetStream(); 
            streamReader =
            new StreamReader(networkStream);
            while (true)
            {

                try
                {
                    
                    string outputString;
                    outputString = streamReader.ReadLine(); // recieves info
                    RecievedMessage = outputString;
                    if (outputString != null) { board.GetMessageFromClient(); } 
                                               //if info isn't null send it out
                }
                catch {  }
            }
        }
Posted
Updated 20-Jul-13 2:48am
v2

1 solution

The proper way to do it would be to use the .BeginReceive and .EndReceieve methods on the socket. MSDN has an example here[^].

This way you avoid the use of threads and the issue you described above. Its a little more coding work but its worth it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900