I want to run a function periodically every 1 second, so after 10 seconds it is executed 10 times. The simplest approach is using a loop like this :
while(true)
{
Thread.Sleep(1000);
function();
}
But the main problem with this approach is that it will not provide any periodic guarantees. I mean if it takes 0.1 seconds to run function() the executions time of the function will be like this : 0, 1.1 , 2.2, 3.3, 4.4 , ...
As I remember, in real time language ADA we have a function sleep-until(#time). Now I'm looking for an alternative in C#.
Any sample code will be appreicated.
System.Threading.Timer timer = new System.Threading.Timer(ThreadFunc, null, 0, 1000);
private static void ThreadFunc(object state)
{
//Do work in here.
}
See MSDN for more info.
You can use Stopwatch
to measure the time. I would also use a For-Loop
instead.
var sw = new System.Diagnostics.Stopwatch();
var timeForOne = TimeSpan.FromSeconds(1);
var count = 10;
for(int i = 0; i < count; i++)
{
sw.Restart();
function();
sw.Stop();
int rest = (timeForOne - sw.Elapsed).Milliseconds;
if (rest > 0)
System.Threading.Thread.Sleep(rest);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With