-2

我正在寻找一些关于使我的代码更高效的建议。我想做的是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.
    }
}

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

非常感谢所有建议!

4

3 回答 3

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");
    }
}
于 2013-04-25T17:27:26.253 回答
1

这不好,因为您每次迭代都会创建并放弃一个全新的计时器。移动

timer = new Timer(Write);

intoMain使其只执行一次,然后SetTimer可以重用这个单个 Timer 对象。

于 2013-04-25T17:26:28.503 回答
0

在 WPF 中:

DispatcherTimer timer = new DispatcherTimer();

timer.Tick += timer_Tick;
timer.Interval = = new TimeSpan(1, 0, 0); //once an hour
timer.Start();

void timer_Tick(object sender, EventArgs e)
{
     //do your updates
}
于 2013-04-25T17:29:29.487 回答