Hi I'm having high CPU usage (15-16%) when running this thread, it is a thread that is supposed to keep looping unless "ssStop" is set to true (which works), however, while it is running I open task manager and I see that the program is using up 15% of the computers processing power, it drops back down to 1-2% once the thread has been exited. Even when using EventWaitHandle which I found searching for this problem online it still remains this high, does anyone know what I'm doing wrong here?:
public void Receive()
{
try
{
bool firstTimeRun = true;
TcpListener ssTcpListener = new TcpListener(IPAddress.Any, 1500);
TcpClient tcpReceiver;
ssTcpListener.Start();
while (!ssStop)
{
//Start listening for connection.
//Accept any incoming connection requests on port 1500.
tcpReceiver = new TcpClient();
if (ssTcpListener.Pending())
{
tcpReceiver = ssTcpListener.AcceptTcpClient();
}
if (tcpReceiver.Connected)
{
//looped for first time; receives whole image.
if (firstTimeRun)
{
//TCP connected. Receive images from contact
NetworkStream receivedNs = new NetworkStream(tcpReceiver.Client);
Bitmap image = new Bitmap(receivedNs);
receivedImage = image;
pboScrnShare.Image = image;
receivedNs.Flush();
firstTimeRun = false;
}
//second time or higher looped; receives difference and overlays it.
else if (!firstTimeRun)
{
NetworkStream receivedNs = new NetworkStream(tcpReceiver.Client);
//Put image into picturebox.
receivedImage2 = new Bitmap(receivedNs);
receivedImage2.MakeTransparent(Color.Black);
Bitmap overlayedImage = new Bitmap(receivedImage.Width, receivedImage.Height);
using (Graphics gr = Graphics.FromImage(overlayedImage))
{
gr.DrawImage(receivedImage, new Point(0, 0));
gr.DrawImage(receivedImage2, new Point(0, 0));
}
try
{
pboScrnShare.Image = overlayedImage;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "pbo second run");
}
receivedImage2.Dispose();
if (this.InvokeRequired) { this.Invoke(new MethodInvoker(delegate() { receivedImage = overlayedImage; })); } else { receivedImage = overlayedImage; }
receivedNs.Flush();
}
tcpReceiver.Close();
}
myEventWaitHandle.WaitOne(10, true);
}
ssTcpListener.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Invited ReceiveSS()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
sleep(1)somewhere in your loop to allow other threads to execute. There are other problems with your code, however. Since it is working code, consider posting it to codereview.stackexchange.com so that you can get some additional feedback. Even if you do use WaitEventHandle, I don't think it will have any impact on your CPU usage unless there's something to do in other threads.