Sync Timer Callback in C#

390 views Asked by At

I would like to create a function that is called periodically (1 second), the function may take more than 1 second. If the function does not complete, a new thread should not be created. If it completes, it should wait till due time. Which timer method would be the best solution in C#?

2

There are 2 answers

0
Sophie Coyne On
Timer timer = new Timer();//Create new instance of "Timer" class.
timer.Interval = 1000;//Set the interval to 1000 milliseconds (1 second).
bool started = false;//Set the default value of "started" to false;
timer.Tick += (sender, e) =>//Set the procedure that occurs each second.
{
    if (!started)//If the value of "started" is false (if it isn't running in another thread).
    {
        started = true;//Set "started" to true to ensure that this code isn't run in another thread.
        //Other code to be run.
        started = false;//Set "started" to false so that the code can be run in the next thread.
    }
};
timer.Enabled = true;//Start the timer.
2
Enigmativity On

Using Microsoft's Reactive Extensions (NuGet "Rx-Main") you can do this:

Observable
    .Interval(TimeSpan.FromSeconds(1.0))
    .Subscribe(n =>
    {
        /* Do work here */
    });

It waits the interval between the subscription calls.