In many cases, our program, before performing the next step, will need to wait for the execution of the previous one, which is most evident in the asynchronous operation, or in the program that uses the message loop mechanism to communicate.
An example of an API:
Our own program is a, need to use API combined with Windows message mechanism, control external program B;
A send a message to B, B to execute, at this time a need to wait for B execution, according to B's execution result, again send the next message to B
The above example, is a very typical delay application.
When it comes to delay, you may be the first to react.
Let's not talk about the accuracy of sleep delay, sleep of a fatal weakness, is the process of sleep, the process is not responsive to external operations, into the state of suspended animation, so, one is the user experience is very poor, moreover, users want to stop halfway, can only wait, or mandatory kill off the program.
Therefore, the sleep at this time is not advisable. What we need is a delay function that can continue to respond to the operation with high precision.
Below, we implement one ourselves:
Using System.Runtime.InteropServices;
[DllImport ("kernel32.dll")]
static extern uint GetTickCount ();
static void Delay (UINT ms) {
UINT start = GetTickCount ();
while (GetTickCount ()-Start < ms) {
application.doevents ();
}
}