简体   繁体   中英

Delay reacting to TextChanged event

I have WinForms application that reacts to keystrokes in a textbox using the TextChanged event. I want to delay reacting until there has been short gap (maybe 300 milliseconds) since the last keystroke. Below is my current code:

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

My problem is that textSearchString.Focused throws a System.InvalidOperationException .

What am I missing?

A System.Threading.Timer runs on a background thread, which means that in order to access UI elements you must perform invocation or use a System.Windows.Forms.Timer instead.

I'd recommend the System.Windows.Forms.Timer solution as that is the easiest. No need to dispose and reinitialize the timer, just initialize it in the form's constructor and use the Start() and Stop() methods:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM