Search code examples
c#timer

Running Timers in the Background c# Console


Wondering if there's a way to have a timer running in the background of a project that can be accessed if the user inputs a certain thing. At the moment this doesn't work

Timer t = new Timer(Program.TimerCallback, null, 0, 1000);
if (Console.ReadLine() == "i")
{
    TimeSpan time = TimeSpan.FromSeconds(Program.seconds);
    string str = time.ToString(@"mm\:ss");
    Console.WriteLine("Time :" + str);
}
public static void TimerCallback(object o)
{
    seconds +=1;
}

I used to have to code above within the Callback but then I couldn't do anything while it was running the timer. Thanks for any help


Solution

  • If I understand correctly, you don't actually need a timer:

    DateTime startTime = DateTime.Now; // Just have a reference time
    if (Console.ReadLine() == "i")
    {
        TimeSpan time = DateTime.Now - startTime; // Compute difference between "now" and "then"
        string str = time.ToString(@"mm\:ss");
        Console.WriteLine("Time :" + str);
    }
    

    should do the trick.

    Subtracting two DateTimes like this gives you a TimeSpan: DateTime.Subtraction Operator

    If you need better precision, you can make use of the StopWatch class, which also has a little more convenient API:

    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    if (Console.ReadLine() == "i")
    {
        TimeSpan time = stopWatch.Elapsed;
        string str = time.ToString(@"mm\:ss");
        Console.WriteLine("Time :" + str);
    }
    

    BUT do not think you can do (micro-)benchmarks with this. If you intend to do so, consider Benchmark.NET (not affiliated).