最近有个项目,需要在客户停止输入X秒后,才执行相应代码,思考后决定用Timer控件实现,代码如下:
Timer timer = new Timer();
private void Form2_Load(object sender, EventArgs e)
{
timer.Interval = 500;//延时500毫秒
timer.Tick += new EventHandler(timer_Tick);
}
void timer_Tick(object sender, EventArgs e)
{
lock (this)
{
timer.Stop();
if (textBox1.Text != string.Empty)
{
//此处执行所需代码
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
lock (this)
{
timer.Stop();
timer.Start();
}
}