我可以更有效地使用 System.Threading.Timer

-2 c# windows-services timer autoresetevent

我正在寻找一些关于使我的代码更高效的建议。我想要做的是让System.Threading.Timer一个每小时左右运行一些工作,这项工作不会很繁重,但我想要一个不占用太多资源的代码。我计划在 Windows 服务中运行此代码。

这是我到目前为止。

class Program
{
    private static Timer timer;

    static void Main(string[] args)
    {
        SetTimer();
    }

    static void SetTimer()
    {
        timer = new Timer(Write);

        var next = DateTime.Now.AddHours(1);

        var nextSync = (int)(next - DateTime.Now).TotalMilliseconds;

        timer.Change(nextSync, Timeout.Infinite);
    }

    static void Write(object data)
    {
        Console.WriteLine("foo");

        SetTimer(); //Call the SetTimer again for the next run.
    }
}
Run Code Online (Sandbox Code Playgroud)

你们有什么感想?我可以让我的代码更有效率吗?

非常感谢所有建议!

Mar*_*der 5

几点:

  • 您不必每小时创建一个新计时器。
  • 将第二个参数设置为无限,使您必须手动重新加载计时器。但是……在这种情况下,你为什么要这样做?
  • 您进行了一项困难的计算,以从现在的一小时形式创建时间跨度:现在 + 1 小时 - 现在。这可以轻松解决。

尝试这个:

class Program
{
    private static Timer timer = new Timer(Write, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));

    static void Main(string[] args)
    {
    }

    static void Write(object data)
    {
        Console.WriteLine("foo");
    }
}
Run Code Online (Sandbox Code Playgroud)