Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sleep-until in c#

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.

like image 763
user1654052 Avatar asked Oct 11 '12 07:10

user1654052


2 Answers

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.

like image 189
nick_w Avatar answered Sep 18 '22 01:09

nick_w


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);
}
like image 37
Tim Schmelter Avatar answered Sep 21 '22 01:09

Tim Schmelter