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#?
Asked
Active
Viewed 368 times
2 Answers
1
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.

Enigmativity
- 113,464
- 11
- 89
- 172
-
Wouldn't this run regardless of whether or not another thread has been completed? – Sophie Coyne Feb 18 '16 at 11:00
-
@Rariolu - No, it's not a `Timer`, it's an `Interval`. It waits for the gap between running each subscription. – Enigmativity Feb 18 '16 at 11:33
0
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.

Sophie Coyne
- 1,018
- 7
- 16