【问题标题】:Program freezes when opening a textfile with over 100,000 lines打开超过 100,000 行的文本文件时程序冻结
【发布时间】:2013-07-11 03:57:32
【问题描述】:

我的代码让用户打开一个文本文件,并且每行文本文件的内容被放置在一个数组中,但是当文本文件的内容超过 100,000 行或更多时,我的程序会冻结。我试过 backgroundworker 但似乎不支持 OpenFileDialog。

它在 1,000 行或更少行上运行良好,但我需要超过 100,000 行的文本才能运行此程序。 有什么办法可以调整它的性能使其不会冻结?

这是我的代码:

 Dim Stream As System.IO.FileStream

    Dim Index As Integer = 0

    Dim openFileDialog1 As New OpenFileDialog()
    openFileDialog1.InitialDirectory = "D:\work\base tremble"
    openFileDialog1.Filter = "txt files (*.txt)|*.txt"
    openFileDialog1.FilterIndex = 2
    openFileDialog1.RestoreDirectory = True

    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        Try

            Stream = openFileDialog1.OpenFile()
            If (Stream IsNot Nothing) Then

                Dim sReader As New System.IO.StreamReader(Stream)
                Do While sReader.Peek >= 0
                    ReDim Preserve eArray(Index)
                    eArray(Index) = sReader.ReadLine
                    RichTextBox3.Text = eArray(Index)
                    Index += 1

                    'Delay(2)
                Loop
                Label1.Text = "0/" & eArray.Length & ""
            End If
        Catch Ex As Exception
            MessageBox.Show(Ex.Message)
        Finally
            If (Stream IsNot Nothing) Then
                Stream.Close()
            End If
        End Try
    End If

End Sub

【问题讨论】:

    标签: vb.net openfiledialog


    【解决方案1】:

    backgroundWorker 中不应有任何 UI。

    你需要做的是:

    • 在主 UI 中提示输入文件名
    • 在 BackgroundWorker.DoWork 中创建流
    • 摆脱数组/redim 数组并使用StringCollection - 如果您真的需要,可以在最后将其转换为数组。
    • 通过 BackgroundWorker.RunWorkerCompleted 引发任何事件

    尽可能避免使用 redim preserve,这太可怕了。

    【讨论】:

    • 是的,这很有效,感谢冻结停止的建议,但我仍在使用 redim preserve。我现在正在阅读有关 StringCollection
    • 这是一篇关于为什么不在循环中使用 redim preserve 的好博客:alfredmyersjr.wordpress.com/2009/02/12/…
    猜你喜欢
    • 2015-07-23
    • 2022-06-25
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2016-06-20
    相关资源
    最近更新 更多