延迟对TextChanged事件做出反应

时间:2016-07-04 16:02:04

标签: c# winforms

我有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

我错过了什么?

2 个答案:

答案 0 :(得分:2)

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();
}

答案 1 :(得分:0)

试试这个..

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