延迟响应TextChanged事件

本文关键字:事件 TextChanged 响应 延迟 | 更新日期: 2023-09-27 17:54:30

我有一个WinForms应用程序,它对使用TextChanged事件的文本框中的击键作出反应。我想延迟反应,直到有一个短的间隙(也许300毫秒),因为上次击键。下面是我当前的代码:

private void TimerElapsed(Object obj)
{
    if (textSearchString.Focused) 
    {  //this code throws exception
        populateGrid();
        textTimer.Dispose();
        textTimer = null;
    }
}
private void textSearchString_TextChanged(object sender, EventArgs e)
{
    if (textTimer != null)
    {
        textTimer.Dispose();
        textTimer = null;
    }
    textTimer = new System.Threading.Timer(TimerElapsed, null, 1000, 1000);
}

我的问题是textSearchString.Focused抛出了一个System.InvalidOperationException

我错过了什么?

延迟响应TextChanged事件

System.Threading.Timer运行在后台线程上,这意味着为了访问UI元素,您必须执行调用或使用System.Windows.Forms.Timer代替。

我推荐System.Windows.Forms.Timer解决方案,因为这是最简单的。不需要处理和重新初始化计时器,只需在表单的构造函数中初始化它,并使用Start()Stop()方法:

System.Windows.Forms.Timer textTimer;
public Form1() //The form constructor.
{
    InitializeComponent();
    textTimer = new System.Windows.Forms.Timer();
    textTimer.Interval = 300;
    textTimer.Tick += new EventHandler(textTimer_Tick);
}
private void textTimer_Tick(Object sender, EventArgs e)
{
    if (textSearchString.Focused) {
        populateGrid();
        textTimer.Stop(); //No disposing required, just stop the timer.
    }
}
private void textSearchString_TextChanged(object sender, EventArgs e)
{
    textTimer.Start();
}

try this.

private async void textSearchString_TextChanged(object sender, EventArgs e)
{
  await Task.Delay(300); 
  //more code
}