Search code examples
c#timerconsole

Alternative to using 'global' variables in a static class when using a TimerCallback


I'm using a TimerCallback method to display statistics to the screen every 5 seconds like this:

var timerCallback = new TimerCallback(_outputDisplayer.SetupThreading);
var stateTimer = new Timer(timerCallback, null, 0, 5000);

I have a static class holding statistics variables that I'm calculating. When the timer goes off a method in the outputDisplayer class is called and displays their values.

public static class Properties
{
  public static decimal PercentOfChocolateIceCream { get; set; }  = 0
  public static decimal PercentOfRedCars { get; set; } = 0
}

Since I'm not calling the method that displays the statistics myself, I've been using fields in this static class. Is there a better way to do this without having the static class and variables?


Solution

  • Use an instance class instead, and pass the instance to the timer's constructor. Your callback can read it from the state argument that is passed to it.

    public class Properties
    {
        public decimal PercentOfChocolateIceCream { get; set; }  = 0
        public decimal PercentOfRedCars { get; set; } = 0
    }
    
    var properties = new Properties();
    var timerCallback = new TimerCallback(_outputDisplayer.SetupThreading);
    var stateTimer = new Timer(timerCallback, properties, 0, 5000);
    
    
    
    void SetupThreading(object? state)
    {
        var properties = (Properties)state;
    
        //etc...