Bulki
Bulki

Reputation: 741

Delaying the search function in keypress actions

I'm trying to delay an action on a textbox. I want to search a large quantity of text for a word. Now I do this with the "textchanged" event. The problem here is, when he reaches a word of more then 3 letters (I've prevented 0-2 wordsearches) the process becomes intensive.

Question: What are my possibilities here?

Code:

private void txtSearch_TextChanged(object sender, EventArgs e)
{
 // delay here
 dosearch(searchbox.text);
}

Upvotes: 3

Views: 4109

Answers (1)

sondergard
sondergard

Reputation: 3234

(Re)start a dispatcher timer every time a key is pressed, and do the search when the timer elapses. Around 200-300 ms delay is usually pretty good.

private DispatcherTimer _searchTimer;

// Initialize timer in constructor with 200 ms delay and register tick event.

private void txtSearch_TextChanged(object sender, EventArgs e)
{
    _searchTimer.Stop();
    _searchTimer.Start();
}

private void OnSearchTimerTick(object sender, EventArgs e)
{
    _searchTimer.Stop()
    Search(searchBox.Text);
}

private void Search(string searchTxt)
{
    // Do search
}

UPDATE: To improve the responsiveness (the above example will lock the UI while searching because the dispatcher timer callback runs on the UI thread), you can execute the search in a separate Task. When the search completes you need to ensure that the result is not stale (that the user has not modified the search text while searching):

private void Search(string searchText)
{
    Task.Run(() =>
        {
            // Execute search

            Dispatcher.Invoke(() =>
            {
                if (searchText == searchBox.Text)
                {
                    // Result is good
                }
            });
    });
}

Upvotes: 11

Related Questions