在C#中,将大文件加载到winform richtextbox中 [英] In C#, Loading large file into winform richtextbox
问题描述
我需要将一个10MB范围的文本文件加载到Winform RichTextBox中,但是我当前的代码冻结了UI.我尝试让后台工作人员进行加载,但这似乎也不是很好.
I need to load a - 10MB range text file into a Winform RichTextBox, but my current code is freezing up the UI. I tried making a background worker do the loading, but that doesnt seem to work too well either.
这是我尝试过的几个加载代码.有什么办法可以改善其性能?谢谢.
Here's my several loading code which I was tried. Is there any way to improve its performance? Thanks.
private BackgroundWorker bw1;
private string[] lines;
Action showMethod;
private void button1_Click(object sender, EventArgs e)
{
bw1 = new BackgroundWorker();
bw1.DoWork += new DoWorkEventHandler(bw_DoWork);
bw1.RunWorkerCompleted += bw_RunWorkerCompleted;
string path = @"F:\DXHyperlink\Book.txt";
if (File.Exists(path))
{
string readText = File.ReadAllText(path);
lines = readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
bw1.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
Invoke((ThreadStart)delegate()
{
for (int i = 0; i < lines.Length; i++)
{
richEditControl1.Text += lines[i] + "\n";
}
});
}
我也尝试:
Action showMethod = delegate()
{
for (int i = 0; i < lines.Length; i++)
{
richEditControl1.Text += lines[i] + "\n";
}
};
推荐答案
这与您如何调用UI更新有关,请检查下面的AppendText
.
It's about how you're invoking the UI update, check the AppendText
bellow.
private BackgroundWorker bw1;
private void button1_Click(object sender, EventArgs e)
{
bw1 = new BackgroundWorker();
bw1.DoWork += new DoWorkEventHandler(bw_DoWork);
bw1.RunWorkerCompleted += bw_RunWorkerCompleted;
bw1.RunWorkerAsync();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
string path = @"F:\DXHyperlink\Book.txt";
if (File.Exists(path))
{
string readText = File.ReadAllText(path);
foreach (string line in readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
AppendText(line);
Thread.Sleep(500);
}
}
}
private void AppendText(string line)
{
if (richTextBox1.InvokeRequired)
{
richTextBox1.Invoke((ThreadStart)(() => AppendText(line)));
}
else
{
richTextBox1.AppendText(line + Environment.NewLine);
}
}
除了读取整个文件的文本外,效率非常低.我宁愿逐块阅读并更新UI.即
In addition to that reading the whole file text is very inefficient. I would rather read chunk by chunk and update the UI. i.e.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
string path = @"F:\DXHyperlink\Book.txt";
const int chunkSize = 1024;
using (var file = File.OpenRead(path))
{
var buffer = new byte[chunkSize];
while ((file.Read(buffer, 0, buffer.Length)) > 0)
{
string stringData = System.Text.Encoding.UTF8.GetString(buffer);
AppendText(string.Join(Environment.NewLine, stringData.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)));
}
}
}
这篇关于在C#中,将大文件加载到winform richtextbox中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!