Time EventHandler
-
I'm making a program to schedule my programs and to shut down my computer in a choosen time but this way my processor is 100 percent, logicaly. How can i change this. while (!(System.DateTime.Now.Equals(shut.getDateTime()))) { } this.Computer_Shutdown(); Please help me. Thank you. :((
-
I'm making a program to schedule my programs and to shut down my computer in a choosen time but this way my processor is 100 percent, logicaly. How can i change this. while (!(System.DateTime.Now.Equals(shut.getDateTime()))) { } this.Computer_Shutdown(); Please help me. Thank you. :((
Add a
Thread.Sleep(1)
into your while loop and cpu usage will drop :) Otherwise you could use a timer to periodically process the following:if (System.DateTime.Now.Equals(shut.getDateTime()))
this.Computer_Shutdown();
-
I'm making a program to schedule my programs and to shut down my computer in a choosen time but this way my processor is 100 percent, logicaly. How can i change this. while (!(System.DateTime.Now.Equals(shut.getDateTime()))) { } this.Computer_Shutdown(); Please help me. Thank you. :((
Using such a busy wait is _really_ bad style. I'd suggest the following: Create a new timer and set it's interval to the amount of milliseconds from now to the desired shutdown time:
Timer shutTimer = new Timer();
shutTimer.Tick += new EventHandler(shutTimer_Tick);
TimeSpan waitDuration = shut.GetDateTime().Subtract(DateTime.Now);
shutTimer.Interval = (int)waitDuration.TotalMilliseconds;
shutTimer.Start();
[...]
private void shutTimer_Tick(object sender, EventArgs e)
{
this.Computer_Shutdown();
}Regards, mav
-
Using such a busy wait is _really_ bad style. I'd suggest the following: Create a new timer and set it's interval to the amount of milliseconds from now to the desired shutdown time:
Timer shutTimer = new Timer();
shutTimer.Tick += new EventHandler(shutTimer_Tick);
TimeSpan waitDuration = shut.GetDateTime().Subtract(DateTime.Now);
shutTimer.Interval = (int)waitDuration.TotalMilliseconds;
shutTimer.Start();
[...]
private void shutTimer_Tick(object sender, EventArgs e)
{
this.Computer_Shutdown();
}Regards, mav
But I can't use a timer because I'm using a thread to do this, i tried and did not work. The idea is great. Thanks. ;)
-
But I can't use a timer because I'm using a thread to do this, i tried and did not work. The idea is great. Thanks. ;)
That's why there are several different types of timers in .NET. If you can't use a
System.Windows.Forms.Timer
(because you don't have a GUI) then aSystem.Timers.Timer
should work fine. The events differ a little, but the concept stays the same: Calculate how long until the desired shutdown time and wind up the timer... Regards, mav