Nick
Nick

Reputation: 29

Perform an action every second

Most resources online say to use a Timer to perform an action every X interval, but this seemed much simpler. Would there be any reason why this would be bad code wise?

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;
        }
    }
}

Upvotes: 2

Views: 4388

Answers (4)

CodeCaster
CodeCaster

Reputation: 151588

This is a "busy wait", and yes, that's bad. You're enhancing the greenhouse effect by letting your CPU waste cycles. The loop will be uselessly executed millions of times per second, while timers let the OS call back your application, so the CPU cycles can be used to actually do something useful, or simply let the CPU go into a lower power state or frequency, saving power.

Therefore, the resources you read that are advising to use a timer, do so for a reason. So save the planet: use a timer.

Upvotes: 12

jgauffin
jgauffin

Reputation: 101130

What loop will consume all available CPU as nothing tells it to slow down.

You could do something like:

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);
        }

    }

which would make it "rest" in each loop iteration

However, is that really nicer than:

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();
        }
    }
}

Upvotes: 3

Alexander
Alexander

Reputation: 149

Yes, your are wasting CPU cycles and possibly lock program execution. Take a look at the Timers in .NET, for example:

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);
}

Upvotes: 2

Timbo
Timbo

Reputation: 28050

Have a look at your task manager while your program is running.

You will see your process with 100/N % CPU load, where N is the total number of CPUs in your system.

Your program basically keeps one CPU busy, thus wasting energy, and taking up resources that other programs could use.

Upvotes: 4

Related Questions