我需要将大约 10MB 范围的文本文件加载到 WPF RichTextBox 中,但我当前的代码卡住了 UI。我尝试让后台工作人员进行加载,但这似乎也不太奏效。
这是我的加载代码。有什么办法可以提高它的性能吗?谢谢。
//works well for small files only
private void LoadTextDocument(string fileName, RichTextBox rtb)
{
System.IO.StreamReader objReader = new StreamReader(fileName);
if (File.Exists(fileName))
{
rtb.AppendText(objReader.ReadToEnd());
}
else rtb.AppendText("ERROR: File not found!");
objReader.Close();
}
//background worker version. doesnt work well
private void LoadBigTextDocument(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
System.IO.StreamReader objReader = new StreamReader( ((string[])e.Argument)[0] );
StringBuilder sB = new StringBuilder("For performance reasons, only the first 1500 lines are displayed. If you need to view the entire output, use an external program.\n", 5000);
int bigcount = 0;
int count = 1;
while (objReader.Peek() > -1)
{
sB.Append(objReader.ReadLine()).Append("\n");
count++;
if (count % 100 == 0 && bigcount < 15)
{
worker.ReportProgress(bigcount, sB.ToString());
bigcount++;
sB.Length = 0;
}
}
objReader.Close();
e.Result = "Done";
}
最佳答案
WPF RichTextBox控件使用Flow Document显示富文本,然后将Flow Document附加到RTB控件,而Windows Form RichTextBox控件直接显示富文本。 这就是 WPF RTB 超慢的原因。 如果您可以使用 WinForm RTB,只需将其托管在您的 wpf 应用程序中即可。 xaml:
<Window x:Class="WpfHostWfRTB.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Grid>
<WindowsFormsHost Background="DarkGray" Grid.row="0" Grid.column="0">
<wf:RichTextBox x:Name="rtb"/>
</WindowsFormsHost>
</Grid>
</Grid>
</Window>
C#代码
private void LoadTextDocument(string fileName, RichTextBox rtb)
{
System.IO.StreamReader objReader = new StreamReader(fileName);
if (File.Exists(fileName))
{
rtb.AppendText(objReader.ReadToEnd());
}
else rtb.AppendText("ERROR: File not found!");
objReader.Close();
}
关于C# - 将大文件加载到 WPF RichTextBox 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/837086/