How to wait a period of time or a function call, depending on how long it takes longer, even when the system time changes?

I have a situation where I do not want to perform a certain function too quickly. I have this code:

DoSomething();
Thread.Sleep(TimeSpan.FromMilliseconds(200));

How can I change this code to run the maximum function time or timeout?

Please note: I cannot use the system time because my software can change the hours of operation of the clock.

So, if it DoSomething()takes 400 MS, it will wait for 400 MS, but if it takes 100 MS, the program will wait for 200 MS.

+1
source share
4 answers

Maybe something like this:

var stopWatch = new StopWatch();
stopWatch.Start();
DoSomething();
stopWatch.Stop();
var diff = 200 - stopWatch.Elapsed.TotalMilliseconds;
if(diff > 0)
    Thread.Sleep(diff);

StopWatch :

, . , . .

:
:

, DoSomething() 400 MS, 400 MS, 100 MS, 200 MS.

, , , 300 MS. , , :

var stopWatch = new StopWatch();
stopWatch.Start();
DoSomething();
stopWatch.Stop();
var timeToSleep = 200;
if(stopWatch.Elapsed.TotalMilliseconds < timeToSleep)
    Thread.Sleep(timeToSleep);
+7

IF V4 .Net, .

- :

 Task.WaitAll(
     Task.Factory.StartNew(()=>DoSomething()),
     Task.Factory.StartNew(()=>Thread.Sleep(200))
     );
+5

DoSomething Stopwatch , .

+3

, , , . Thread.Join() , .

// Define the threads and there startpoint
Thread thread1 = new Thread(DoSomething);
Thread thread2 = new Thread(() => Thread.Sleep(2000));

// Start both threads
thread1.Start();
thread2.Start();

// Wait for both threads to be finished.
thread1.Join();
thread2.Join();
+1

Source: https://habr.com/ru/post/1533327/


All Articles