【发布时间】:2015-05-11 20:01:13
【问题描述】:
我有一个 RichTextBox,一旦用户加载一个文件,我的程序就会继续扫描整个文件以更改某些单词的颜色。这是我的代码:
static Regex cKeyWords = new Regex(@"\b(?=[a-gilr-w])(?:
s(?:hort|i(?:gned|zeof)|t(?:atic|ruct)|witch) | c(?:ase|har|on(?:st|tinue)) |
e(?:lse|num|xtern) | i(?:f|nt) | f(?:loat|or) | d(?:o|efault|ouble) | un(?:ion|signed) |
re(?:gister|turn) | vo(?:id|latile) | while | break | long | typedef | auto | goto
)\b",
RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
...
programTextBox.Enabled = false;
int selectStart = this.programTextBox.SelectionStart;
programTextBox.SuspendLayout();
MatchCollection matches = cKeyWords.Matches(programTextBox.Text);
foreach (Match match in matches)
{
if (match.Index == 0)
programTextBox.Select(match.Index, match.Length/* - 1*/);
else
programTextBox.Select(match.Index + 1, match.Length - 1);
programTextBox.SelectionColor = Color.Blue;
}
programTextBox.Select(selectStart, 0);
programTextBox.SelectionColor = Color.Black;
programTextBox.Enabled = true;
programTextBox.ResumeLayout();
问题:我的代码需要大约 5 秒半的时间来扫描并更改包含 200,000 个字符的文件中所有关键字的颜色。
之前有人告诉我,我不应该将正则表达式用于那种东西,但在做了几次测试后,我发现:MatchCollection matches = cKeyWords.Matches(programTextBox.Text);
只需要大约 0.1s 和删除
programTextBox.SelectionColor = Color.Blue;
将我的代码的总执行时间从 5.5s 减少到大约 0.3s
怎么样?为什么?最重要的是:我能做什么?
【问题讨论】:
-
哦,是的,忘记提了。是的。
-
在循环之前暂停绘画并在循环之后立即恢复。 stackoverflow.com/questions/3282384/… 或更好地找到支持语法高亮的控件。有几个可用的开源库。
-
暂停布局并在你完成更改后像@SriramSakthivel 建议的那样恢复,然后调用 RichTextbox.Refresh()。这将仅绘制可见项目。我是为我的 datagridview 项目做的,节省了很多时间。
标签: c# regex winforms richtextbox syntax-highlighting