3

在谈论我的问题之前,我想澄清一下,这不是一个关于如何打开大文本文件的问题。

我已经做了。这是一个 150MB 的 .txt 文件,我在 1 秒左右将其转储到字典对象中。在此之后,我想在 UI 组件中显示它。

我曾尝试使用 TextBox,但直到现在应用程序窗口还没有出现(在我单击 F5 后已经 5 分钟).....

所以问题是显示大量字符的更好的 UI 组件是什么(我在字典对象中有 393300 个元素)

谢谢

更新:

 private void LoadTermCodes(TextBox tb)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            StreamReader sr = new StreamReader(@"xxx.txt");
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                string[] colums = line.Split('\t');
                var id = colums[4];
                var diagnosisName = colums[7];

                if (dic.Keys.Contains(id))
                {
                    var temp = dic[id];
                    temp += "," + diagnosisName;
                    dic[id] = temp;
                }
                else
                {
                    dic.Add(id, diagnosisName);
                }

                //tb.Text += line + Environment.NewLine;
            }

            sw.Stop();
            long spentTime = sw.ElapsedMilliseconds;

            foreach (var element in dic)
            {
                tb.Text += element.Key + "\t" + element.Value + Environment.NewLine;
            }

            //tb.Text = "Eplased time (ms) = " + spentTime;
            MessageBox.Show("Jie shu le haha~~~ " + spentTime);
        }
4

1 回答 1

4

The long running issue you're seeing is possibly due to how String are handled by the c# runtime. Since Strings are immutable what's happening every time you're calling + on them it's copying the String so far and the next small part into a new memory location and then returning that.

There's a good couple of articles by Eric Lippert here: Part 1 and Part 2 that explain it under the hood.

Instead, to stop all of this copying, you should use a StringBuilder. What this will do to your code is:

private void LoadTermCodes(TextBox tb)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    StreamReader sr = new StreamReader(@"xxx.txt");
    string line;

    // initialise the StringBuilder
    System.Text.StringBuilder outputBuilder = new System.Text.StringBuilder(String.Empty);
    while ((line = sr.ReadLine()) != null)
    {
        string[] colums = line.Split('\t');
        var id = colums[4];
        var diagnosisName = colums[7];

        if (dic.Keys.Contains(id))
        {
            var temp = dic[id];
            temp += "," + diagnosisName;
            dic[id] = temp;
        }
        else
        {
            dic.Add(id, diagnosisName);
        }
    }

    sw.Stop();
    long spentTime = sw.ElapsedMilliseconds;

    foreach (var element in dic)
    {
        // append a line to it, this will stop a lot of the copying
        outputBuilder.AppendLine(String.Format("{0}\t{1}", element.Key, element.Value));
    }

    // emit the text
    tb.Text += outputBuilder.ToString();

    MessageBox.Show("Jie shu le haha~~~ " + spentTime);
}
于 2013-07-12T02:35:40.423 回答