Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

how to recalculate something ~once per second?

I need to do some pretty fast recalculation ~every second. What is the best way to do that? Is using dedicated thread and Thread.Sleep is ok?

        Task.Factory.StartNew(() => 
        {
            while (true)
            {
                RecalculateState();
                Thread.Sleep(1000);
            }
        }, TaskCreationOptions.LongRunning);

Upvotes: 0

Views: 199

Answers (4)

Tigran
Tigran

Reputation: 62276

You can use System.Timers.Timer with 1 second interval.

It already runs in a new thread .

Pay attention on fact, that if RecalculateState runs longer than expected interval (for 1000 of reasons) you have to deal with calls overlapping, so you have to manage that case in some way.

One of possible solutions, is to run a new code only after execution of the method finished, and measure difference between execution time and interval. But this is not so easy task to do. Fortunatelly someone already thought about that problem.

Can have a look on Reactive Extensions that in latest build payed special attention on time dependent execution.

Upvotes: 1

DAKL
DAKL

Reputation: 39

I would suggest to use a timer for this.

member:

private readonly Timer _timer;

instantiate the timer in the constructor for instance:

_timer= new Timer(OnTimerEllapsed, null, 0, 1000);

callback:

private void OnTimerEllapsed(object sender)
{
    RecalculateState();
}

Upvotes: 0

Jonas W
Jonas W

Reputation: 3260

Can't you use a timer and make a ontimed event? Something like this ?

Observable.Timer(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(1)).Timestamp()
       .Subscribe(MyOnTimedEventMethod);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502116

That would work - but another alternative would be to use a timer, e.g. System.Threading.Timer or System.Timers.Timer.

You should think about:

  • What do you want to happen if it takes more than a second to recalculatte state?
  • Is your RecalculateState method entirely safe to be called from arbitrary threads?

Upvotes: 2

Related Questions