代码之家  ›  专栏  ›  技术社区  ›  Rich Faheem Sharif

使用TimerCallback时在静态类中使用“全局”变量的替代方法

  •  0
  • Rich Faheem Sharif  · 技术社区  · 5 年前

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

    我有一个静态类,它包含我正在计算的统计变量。当计时器关闭时,将调用outputDisplayer类中的方法并显示其值。

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

    0 回复  |  直到 5 年前
        1
  •  1
  •   John Wu    5 年前

    state 传递给它的参数。

    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...