sleep-until in c#

user1654052 picture user1654052 · Oct 11, 2012 · Viewed 7.8k times · Source

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.

Answer

nick_w picture nick_w · Oct 11, 2012
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.