业务场景:有主表、子表两个GridView点击主表的行,会自动读取主表对应的子表数据
但是如果反复点击会导致反复读取,其实反复点击的时候只需要最后一次执行查询,前面的几次点击都是无意义操作
根据这一需求设计了一个函数:
private static List<System.Windows.Forms.Timer> Tup = new List<System.Windows.Forms.Timer>();
/// <summary>
/// 延时执行
/// </summary>
/// <param name="easySub">需要执行的代码/函数</param>
/// <param name="keyName">任务分组</param>
/// <param name="timeOut">等待timeOut时间后执行代码,如果当前分组中进入新的任务则前面的任务放弃,执行新的任务</param>
/// <param name="chkStatus">等待一定时间且循环验证chkStatus</param>
public static void DelayRun(Action easySub, string keyName, int timeOut = 501)
{
System.Windows.Forms.Timer lastTimer = Tup.Find(t => t.Tag.ToStringEx() == keyName);
if (lastTimer != null)
{
lastTimer.Enabled = false;
lastTimer.Enabled = true;
}
if (lastTimer == null)
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = timeOut;
t.Enabled = true;
t.Tag = keyName;
Tup.Add(t);
t.Tick += delegate (object sender, EventArgs e)
{
((System.Windows.Forms.Timer)sender).Enabled = false;
string name = keyName;
easySub();
};
}
}
本文介绍了一种用于延时执行查询的机制,通过该机制可以避免因频繁点击导致的重复查询问题。具体实现方式是在每次点击时启动一个定时器,若在设定的时间内有新的点击事件发生,则取消前一次的定时器并重新计时;到达指定时间后执行查询操作。
1965

被折叠的 条评论
为什么被折叠?



