开发者

How to wait for a period of time or function call, whichever takes longest even when the system time changes?

I have a situation where I don't want to be executing a particular function too quickly. I currently have this code:

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

How can I change this code to run for the max of the function time or the wait time?

P开发者_StackOverflow中文版lease note: I can't use the system time because my software can change the clock time.

So, if DoSomething() takes 400 MS, it would only wait 400 MS, but if it took 100 MS, the program would wait 200 MS.


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);

The StopWatch class is not using the system clock for its measurement:

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time.

Update:
You write:

So, if DoSomething() takes 400 MS, it would only wait 400 MS, but if it took 100 MS, the program would wait 200 MS.

I first thought, this was not what you wanted, because, in the second case, it takes a total time of 300 MS. But if that indeed is, what you want, take this code:

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


IF can use the V4 of .Net, create two tasks and wait for both ended.

Something like this :

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


You could time the duration of DoSomething with a Stopwatch and wait the difference between your target time and the duration of the method call or nothing if the method call exceeds your wait time.


You could make two threads, one that does the actual work, and a second thread that sleeps for a given time. Then you use Thread.Join() in the main thread to wait for the two threads to end.

// 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜