计时器未执行在UtilityClass构造函数中定义的计时器

时间:2019-04-19 04:22:43

标签: c# timer

我想每10秒钟执行一次C#方法,并且在UtilityClass类构造函数中使用该方法,但是该方法未执行且没有任何输出。

class Program
{
    static void Main(string[] args)
    {
        UtilityClass utilityClass = new UtilityClass();
    }
}

public class UtilityClass : IDisposable
{
    private readonly System.Timers.Timer _Timer;

    public UtilityClass()
    {
        _Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
        _Timer.Elapsed += (sender, eventArgs) =>
        {
            ExecuteEvery10Sec();
        };
    }

    private void ExecuteEvery10Sec()
    {
        Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
    }

    public void Dispose()
    {
        _Timer.Dispose();
    }
}

1 个答案:

答案 0 :(得分:1)

有两个问题:一-程序立即终止,因此计时器被销毁。你应该等一下。例如,等待10分钟:

class Program
{
    static void Main(string[] args)
    {
        using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
        {
            System.Threading.Thread.Sleep(10000 * 60); // Waits X milliseconds
        }
    }
}

编辑:

您还可以执行无限循环,因此ser只能通过控制台的X按钮(或Ctrl + C)退出。所以:

class Program
{
    static void Main(string[] args)
    {
        using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
        {
            while (true) { }
        }
    }
}

两个-您应该通过将计时器的Enabled属性设置为true来启动计时器:

public class UtilityClass : IDisposable
{
    private readonly System.Timers.Timer _Timer;

    public UtilityClass()
    {
        _Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
        _Timer.Enabled = true;
        _Timer.Elapsed += (sender, eventArgs) =>
        {
            ExecuteEvery10Sec();
        };
    }

    private void ExecuteEvery10Sec()
    {
        Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
    }

    public void Dispose()
    {
        _Timer.Dispose();
    }
}