在 C# 中处理大文本
我从 RichTextBox 收到 15.000(可以更多)行,我需要为每行添加一些值。 为了使程序不会锁定,最好的方法是什么?
目前,我正在处理作为线程运行的循环中的行:
public void Process()
{
string[] lines;
string line;
string foo = " baa";
if (richTextBox1.InvokeRequired)
{
lines = (string[])Invoke((ReadLines)delegate
{
return /* read .Lines[] from richTextBox1 */
});
int max = lines.Length;
for (int i = 0; i < max; i++)
{
line = lines[i];
if (..)
{
lines[i] += "foo";
}
}
Invoke((Update)delegate
{
/* set new lines to RichTextBox1 */
});
}
}
然后:
Thread th1 = new Thread(Process);
th1.Start();
但它仍然锁定。最好的方法是什么? 提前致谢。
I receive 15.000(can be more) lines from RichTextBox, I need to add some value to each line.
What's the best way to do this, so that the program does not lock up?
Currently, I'm processing the lines in a loop which is running as a thread:
public void Process()
{
string[] lines;
string line;
string foo = " baa";
if (richTextBox1.InvokeRequired)
{
lines = (string[])Invoke((ReadLines)delegate
{
return /* read .Lines[] from richTextBox1 */
});
int max = lines.Length;
for (int i = 0; i < max; i++)
{
line = lines[i];
if (..)
{
lines[i] += "foo";
}
}
Invoke((Update)delegate
{
/* set new lines to RichTextBox1 */
});
}
}
and Then:
Thread th1 = new Thread(Process);
th1.Start();
but it still locks up. What's the best way to do this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 BackgroundWorker 控件。
Try a BackgroundWorker control.
我很遗憾地说,但最好的选择不是使用文本框,而是使用专为部分更新和处理大量文本而设计的编辑器组件(例如 SyntaxEdit)。 UI 不会因您的处理而锁定,但因为文本框在处理大文本时效率低下,并且文本框在更新时会阻塞 UI 线程。如果不重写它就无法工作。可以这么说,你比它的规格大了 14.900 行。每次更新框中的文本时,它都会开始一个非常缓慢的重绘周期。您无法中断它,因此所有线程都无济于事 - 因为 UI 在更新周期结束之前不会响应。
还有其他“真正的文本编辑器”组件也可以处理更大的文本。
I am sorry to say, but your best bet is NOT to use a text box but get an editor component (SyntaxEdit for example) that is designed for partial updates and handling large amounts of text. The UI does not lock up due to your processing but bevccause the text box just is inevfficient with large texts and the text box blocks the UI thread while it updates. It is not going to work without rewriting it. You are 14.900 lines larger than the spec for it, so to say. Every time you update the text in the box, it starts a really slow redrawing cycle. One that you can not interrupt, so all threading wont help - because the UI is unresponsibve until this update cycle is ended.
There are other components for "real text editors" that also are prepared to handle much larger text.
在带有一些进度指示的
BackgroundWorker
中运行可能是您最好的选择(如果您必须使用 RichTextBox)。即使是一张旋转的 AJAX 图像也可能足够了。Running in a
BackgroundWorker
with some indication of progress may be your best bet (if you must use the RichTextBox). Even one of those spinning AJAX images may be enough.