0

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!");
        }
    }
}
AJ_
  • 3,787
  • 10
  • 47
  • 82
  • 6
    The program exits before the timer gets to run. Try adding `Console.ReadLine()` to the end of `Main`. – 001 Aug 28 '19 at 22:49
  • Your timer uses a background thread, and background threads don't keep a process from exiting. Only foreground threads do, and your only foreground thread exits as soon as it's done with the `WriteLine()` call. See marked duplicates for various techniques to keep a console program running long enough to see it do something. – Peter Duniho Aug 29 '19 at 00:49

1 Answers1

0

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