سؤال

I´m looking for some advice about making my code more efficient. What I would like to do is to have a System.Threading.Timer that runs some job every hour or so, the job is not going to be very heavy but I would like to have a code that does not take much of resources. I plan to run this code in a windows service.

This is what I have so far.

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

What do you guys think? Can I make my code more efficient?

All advice is much appreciated!

هل كانت مفيدة؟

المحلول

Several points:

  • You do not have to create a new timer every hour.
  • Setting the second parameter to infinite, makes you have to reload the timer manually. But... In this case, why should you?
  • You make a difficult calculation to create a timespan from one hours form now: now + 1 hour - now. This can solved easily.

Try this:

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");
    }
}

نصائح أخرى

This is not good, since you create and abandon a brand new timer each iteration. Move

timer = new Timer(Write);

into Main so that it only executes once, then SetTimer can reuse this single Timer object.

In 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
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top