有时会在事件中执行比较繁琐的函数,,但是同时 这事件又有可能会频发触发,影响用户体验
比如一个serach 搜索框,按住Del时 会频繁触发,每删除一个字都会触发一次
解决方案
1制定定时器
2一个线程递减定时器
3当定时器被减到0时触发事件
4事件重复执行时会重置定时器
这样起到延迟作用
设定全局变量,判定条件与定时器(频繁读取控件会导致内存溢出,建议使用变量)
string thisWhere = "";
string lastWhere = "";
int _i = 0;
扫描二维码关注公众号,回复:
6024046 查看本文章
写一个重复事件线程
private void search()
{
Thread t = new Thread(() =>
{
while (true)
{
Thread.Sleep(10);
if (_i != 0)
{
Invoke(new Action(() => { _i--; }));
toolStripStatusLabel1.Text = _i.ToString();
}
else
{
if ((lastWhere!= thisWhere) && (thisWhere != ""))
{
DataRow[] dr1 = _dtall.Select("name like '%" + thisWhere + "%' or 字段名 like '%" + thisWhere + "%' or 说明 like '%" + thisWhere + "%' or 字段说明 like '%" + thisWhere + "%'");
Invoke(new Action(() => { lastWhere = textBox1.Text; }));
}
Thread.Sleep(100);
}
}
});
t.Start();
}
事件执行函数,重置定时器与条件
private void textBox1_TextChanged(object sender, EventArgs e)
{
_i = 100;
thisWhere = textBox1.Text;
}
后期可根据这个思路封装控件