문제

How can I manage my code to exactly wait for a certain amount of time (say 10s), if all * time functions on the system are not reliable and return immediately ?

Sleep(10000); // Do not sleep for 10s and execute directly the next function
MyFunction();

The solution should if possible, consume the fewer possible CPU cycles.

Of course they are no internet connection available

*WaitForSingleObject, GetSystemTime, RDTSC and so on...

도움이 되었습니까?

해결책

It's not possible. If you don't have access to a working API for keeping track of time, then you cannot keep track of time.

Your best bet is probably to write a "useless" loop that does nothing but waste time, and then figure out how many times that loop needs to run in order to delay the program by the amount that you need. This will, of course, consume a lot of CPU cycles.

You might be able to avoid consuming so many CPU cycles by performing some useless activity which is I/O-bound, like repeatedly opening and closing a file.

다른 팁

I think this is what you are after:

using System.Threading.Tasks;

var task = Task.Run(() => MyFunction());
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("MyFunction did not complete in time.");

Since you already attempt to Sleep() in your example code, I assume that the computer's timer is reliable enough to make this work.

Further Reading
Crafting a Task.TimeoutAfter Method

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top