[英]Perform an action every second
在線上的大多數資源都說每個X間隔使用一個Timer來執行一個動作,但這似乎要簡單得多。 出於某種原因,這將是不好的代碼嗎?
static void Main(string[] args)
{
int prevTick = 0;
while (true)
{
int curTick = DateTime.Now.Second;
if (curTick != prevTick)
{
//Perform action in here
Console.WriteLine("tick");
prevTick = curTick;
}
}
}
這是一個“忙碌的等待” ,是的,這很糟糕。 您可以通過浪費CPU周期來增強溫室效應。 每秒將無用地執行該循環數百萬次,而計時器則使OS回調您的應用程序,因此可以使用CPU周期來實際執行一些有用的操作,或者只是讓CPU進入低功耗狀態或頻率,從而節省了時間功率。
因此,您閱讀的建議使用計時器的資源是有原因的。 因此,拯救地球:使用計時器。
在程序運行時,查看任務管理器。
您將看到進程具有100 / N%的CPU負載,其中N是系統中的CPU總數。
您的程序基本上使一個CPU繁忙,從而浪費了能量,並占用了其他程序可以使用的資源。
什么循環都會消耗所有可用的CPU,因為沒有任何跡象表明它會變慢。
您可以執行以下操作:
static void Main(string[] args)
{
int prevTick = 0;
while (true)
{
int curTick = DateTime.Now.Second;
if (curTick != prevTick)
{
//Perform action in here
Console.WriteLine("tick");
prevTick = curTick;
}
Thread.Sleep(100);
}
}
這將使其在每次循環迭代中“靜止”
但是,真的比以下更好:
using System;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
private static Timer _timer;
private static void Main(string[] args)
{
_timer = new Timer(state => {
Console.WriteLine("Doing something");
}, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
Console.WriteLine("Press ENTER to quit the application");
Console.ReadLine();
}
}
}
是的,您正在浪費CPU周期,並可能鎖定程序執行。 看一下.NET中的Timers,例如:
public static void Main(string[] args)
{
timer = new System.Timers.Timer(1000); // 1 seconds
timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
timer.Interval = 1000;
timer.Enabled = true;
Console.WriteLine("Press the enter key to stop the timer");
Console.ReadLine();
}
private static void OnTimerElapsed(object source, ElapsedEventArgs e){
Console.WriteLine("Timer elapsed at {0}", e.SignalTime);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.