在很多时候,我们的程序,在执行下一步操作之前,需要等待上一步的执行完成,这种延时等待的方式在异步操作,或者是利用消息循环机制通信的程序中,最为体现的明显。
 
举个API的例子:
 
我们自己的程序是A,需要利用API结合Windows 消息机制,控制外部程序B;
 
A向B发送一个消息,B去执行,此时A需要等待B执行完后,根据B的执行结果,再次向B发送下一个消息
 
 
 
上面的例子,是个很典型的延时应用。
 
说到延时,大家可能第一反应,就是 Sleep 。
 
先不谈 Sleep 延时的精度如何,Sleep 的一个致命的弱点,就是 Sleep 的过程中,进程是不能响应外部操作的,变成了假死状态,这样的话,一个是用户体验很差,再者,用户想中途终止也不行,只能干等,或者强制 KILL 掉程序。
 
 
 
所以,此时的Sleep是不可取的。 我们需要的,是一个可以继续响应操作,而且精度高的延时函数。
 
下面,我们自己实现一个:
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 
10 using System.Runtime.InteropServices;
11 
12 namespace 延时
13 {
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19         }
20 
21         private void Form1_Load(object sender, EventArgs e)
22         {
23             //Delay(10000);
24             label1.Text = "延时测试";
25         }
26 
27         [DllImport("kernel32.dll")]
28         static extern uint GetTickCount();
29         static void Delay(uint ms)
30         {
31             uint start = GetTickCount();
32             while (GetTickCount() - start < ms)
33             {
34                 Application.DoEvents();
35             }
36         }
37         
38         //procedure Delay(const ms: Cardinal); //ms是延时的时长,单位是毫秒
39        
40     }
41 }