C# - 将大文件加载到WPF RichTextBox中?

6 c# wpf richtextbox

我需要将一个~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";
    }
Run Code Online (Sandbox Code Playgroud)

Ala*_*ker 0

为什么不添加到字符串变量(或者甚至使用 StringBuilder),然后在完成解析后将值分配给 .Text 属性?