实施搜索和突出显示 - 当突出显示速度缓慢时如何避免延迟? [英] Implementing search&highlight - how can I avoid delays when highlight is slow?

查看:44
本文介绍了实施搜索和突出显示 - 当突出显示速度缓慢时如何避免延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 RichText,想实现一个高亮搜索,就像你在 VS 或 Chrome 中看到的那样.我得到了一个相当有效的实现:

I have a RichText, and want to implement a highlighting search, like you see in VS or Chrome. I got a fairly-working implementation going:

private void _txtSearch_TextChanged(object sender, EventArgs e)
{
    new RichTextNode(richTextBox1).Highlight(_txtSearch.Text);
}

public void Highlight(string text)
{
    textBox.BeginUpdate();   // Extension, implemented with P/Invoke

    textBox.SelectionStart = 0;
    textBox.SelectionLength = textBox.Text.Length;
    textBox.SelectionBackColor = textBox.BackColor;

    int highlights = 0;

    if (!string.IsNullOrEmpty(text))
    {
    int pos = 0;

    string boxText = textBox.Text;
    while ((pos = boxText.IndexOf(text, pos, StringComparison.OrdinalIgnoreCase)) != -1 && (highlights++) < 500)
    {
        textBox.SelectionStart = pos;
        textBox.SelectionLength = text.Length;

        textBox.SelectionBackColor = Color.Yellow;
        pos += text.Length;
    }
    }

    textBox.EndUpdate();  // Extension, implemented with P/Invoke
}

但是,我想支持大量文本 - 最多 2MB.当有大量文本时,每次更新需要 250 毫秒.对于单次搜索来说没问题 - 但是,我的搜索是增量搜索,这意味着如果用户输入 10 个字母的作品,每个字母都会在 250 毫秒后出现,这看起来很糟糕.

However, I want to support large amounts of text - up to 2MB. When there's a lot of text, each such update takes 250ms. That's OK for a single search - however, my search is incremental, which means that if the user type a 10-letter work, each letter appears after 250ms, which looks bad.

我使用计时器实现了等待:

I implemented a wait using a timer:

private void _txtSearch_TextChanged(object sender, EventArgs e)
{
    performSearch.Stop();
    performSearch.Interval = 100; // Milliseconds
    performSearch.Start();
}

private void performSearch_Tick(object sender, EventArgs e)
{
    new RichTextNode(richTextBox1).Highlight(_txtSearch.Text);
    performSearch.Stop();
}

这很有效.但是,当文本很短时,它会减慢增量搜索的速度,这是次优的.我想我可以计算字符数,但这感觉就像一个黑客......

This works fairly well. However, it slows down the incremental search when the text is short, which is sub-optimal. I guess I could count the chars, but that feels like a hack...

理想情况下,我不想在有额外的击键时突出显示:

Ideally, I'd like not to highlight when additional keystrokes are coming:

private void _txtSearch_TextChanged(object sender, EventArgs e)
{
    if (!_txtSearch.Magic_are_additional_TextChanged_events_already_queued())
        new RichTextNode(richTextBox1).Highlight(_txtSearch.Text);
}

有没有办法做到这一点?或者计时器解决方案是我所能希望的最好的解决方案吗?

Is there a way to do this? Or is the timer solution the best I can hope for?

推荐答案

我最终使用了问题中描述的计时器解决方案,延迟了 1 毫秒.

I ended up using the timer solution described in the question, with a delay of 1ms.

这篇关于实施搜索和突出显示 - 当突出显示速度缓慢时如何避免延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆