在richTextBox1中突出显示匹配的字符串时,应用程序无响应;输入大的.txt文件

时间:2014-04-28 19:20:13

标签: c# winforms

我正在创建一个简单的日志解析/读取应用程序,在尝试突出显示匹配的字符串(用户定义的输入)时会变得无响应,并且在richTextBox1内找到报告日志文件行字符串以查找大文本文件(1.5 Mb或更大)。小文本文件工作正常。匹配的线条看起来很好。尝试突出显示匹配的字符串时会出现问题(越来越多地找到匹配的字符串)。

//application has user select *.txt file and assign contents to string[] logContents, not streaming file.
//list of matched strings is made
//matched strings are displayed in richTextBox1

StringBuilder RTBtext = new StringBuilder(richTextBox1.Text);
if (displayMatched != null && displayMatched.Length > 0)
{
    //displays line of log file that matched the entered string
    for (int s = 0; s < displayMatched.Length; s++)
    {
        RTBtext.Append(displayMatched[s] + Environment.NewLine);
    }
}
richTextBox1.Text = RTBtext.ToString();

//newline \n added between matched line to increase readability

//Performance debugging shows "hot lines" with large CPU usage start here:
while (index < richTextBox1.Text.ToUpper().LastIndexOf(this.userInput1))
{
    richTextBox1.Find(this.userInput1, index, richTextBox1.Text.Length,RichTextBoxFinds.None);
    richTextBox1.SelectionColor = Color.White;
    richTextBox1.SelectionBackColor = Color.Blue;
    index = richTextBox1.Text.ToUpper().IndexOf(this.userInput1, index) + 1;
}

程序另一部分中的类似样式循环执行没有问题。索引有问题吗?是什么让CPU如此努力?性能调试状态System.Windows.Forms.RichTextBox.get_Text();是最大的瓶颈。

我尝试了richTextBox1.SuspendLayoutResumeLayout没有运气(也是RTB1.SuspendPainting / ResumePainting)。

是否可以一次仅突出显示约200行匹配的字符串,然后继续richTextBox1.VScrollBar?如果是这样,那么实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

根据我的经验,RichTextBox不能很好地同时加载大量(兆字节+)的文本。

我的建议是在调用搜索操作时直接处理文本文件,并将所有匹配字节偏移量和长度存储到单独的哈希集/字典中。

一旦你有一个行号和字节偏移的集合,你可以根据滚动位置(也就是无限滚动)动态地将文本写入RichTextBox。每次将新文本附加到RTB时,都要检查在上一步中创建的哈希集中的字节位置。如果找到匹配的字节偏移量,则此时将继续标记文本。在添加RTB时,不要忘记从RTB的开头删除文本。

我亲自处理此应用程序的方式是,除了上述内容之外,还有一个单独的摘要视图,其中包含匹配的行号及其内容。通过这种方式,我可以为所有匹配项提供类似grep的文档视图。单击摘要视图匹配项时,它会将RTB主视图滚动到文档中的该点,以便我可以检查关注项周围的条目。

我之前使用过这样的技术来处理千兆字节大小的日志文件。

相关问题