Screensaver application 100% CPU usage

W

wushupork

I have written a screensaver application in C# .NET and have noticed
that whenever the animation loop is running - CPU usage always spikes
up close to 100%. My application uses a paint thread which is set at
100ms.

the program looks sort of like this:

// constructor
public Form1()
{
InitializeComponent();

// initialization code

tmrPaintRefresh=new System.Timers.Timer(100);
tmrPaintRefresh.Elapsed+=new
System.Timers.ElapsedEventHandler(tmrPaintRefresh_Elapsed);

}


private void tmrPaintRefresh_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
// update animation variables

Invalidate();
}

protected override void OnPaint(PaintEventArgs e)
{
// contains only code to draw objects on the screen
}


The program works fine and everything looks as it should but CPU usage
is abnormally high.

my question is: where should I be calling Application.DoEvents();?

how can I restructure it so that it is not so CPU intensive. All it is
doing is animating text on the screen; it should not be such a CPU
hog.

Thanks much,

wushupork
 
G

Greg Ewing [MVP]

wushupork, just to test things out, try putting a thread.Sleep(100) after
Invalidate() and see if that changes your CPU issue.
 
W

wushupork

Thanks Greg,

That seemed to have solved my problem. On a related note, I have a
system tray app that communicates with the screensaver. All it does is
listens for a message on a port from the screensaver using a
TcpListener.

How do I write a simple socket app so that it does not do a busy wait.

Right now my app looks like this

// event handler for form load
private void Form1_Load(object sender, System.EventArgs e)
{
thread1 = new Thread(new ThreadStart(Listen));
thread1.IsBackground = true;
}

private void Listen()
{
Socket socketForClient;
//TcpListener is listening on the given port...
TcpListener tcpListener = new TcpListener(SCREENSAVER_PORT);

try
{
tcpListener.Start();

while (blnListening)
{

if (tcpListener.Pending())
{
//Accepts a new connection...
socketForClient = tcpListener.AcceptSocket();

if (socketForClient.Connected)
{
// do my stuff
}

socketForClient.Close();
}

// newly added sleep to free up some CPU
Thread.Sleep(100);

}
}
catch(Exception e)
{
Console.WriteLine(e.ToString()) ;
}
finally
{
tcpListener.Stop();
}

// end of code

since adding the Thread.Sleep(100) here, the CPU isn't so busy, but I
am getting the feeling that it is still doing a busy wait. What should
I be doing?

thanks,

wushupork
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top