Search code examples
c#multithreading.net-coretimer

Dotnet - Threading Timer Not Running


I have been reading about the c# Threading Timer, and wanted to use it in my console application. I created a standalone project so i could test it out, and i have been unable to get a simple timer to run. When i run the code below, all i get from the console is the hello world message, but i dont see any timer output. I changed it to write the output to a file, to see if it was just running in the background. However, that also resulted in nothing. I'm using dotnet (2.1) as the run-time if that has anything to do with it.

Does anyone see a reason why the code below does not start a timer ?

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static Timer _timer = null;
        static void Main(string[] args)
        {
            _timer = new Timer(x =>
            {
                Console.WriteLine("Timer is running");

            }, null, 1000, Timeout.Infinite);

            Console.WriteLine("Hello World!");
        }
    }
}

Solution

  • This will wait for the timer to finish ONCE, if you however wish to run the timer "infinitely" long (until enter key is pressed) I suggest using Console.ReadLine() as @Johnny Mopp wrote above

    Assuming you still want to use Timeout.Infinite - Create a Boolean which we will update once timer finishes.

    bool TaskFinished = false;
    

    then run a while loop where you want to wait until timer is finished.

    while(!TaskFinished);
    

    Example:

    using System;
    using System.Threading;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static Timer _timer = null;
            static void Main(string[] args)
            {
                bool TaskFinished = false;
                _timer = new Timer(x =>
                {
                    Console.WriteLine("Timer is running");
                    TaskFinished = true;
    
                }, null, 1000, Timeout.Infinite);
    
                Console.WriteLine("Hello World!");
                while(!TaskFinished);
            }
        }
    }