0

我的代码允许用户打开一个文本文件,并且每行文本文件的内容被放置在一个数组中,但是当文本文件的内容超过 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
4

1 回答 1

2

backgroundWorker 中不应该有任何 UI。

你需要做的是:

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

如果可以,请避免使用 redim preserve,这太可怕了。

于 2013-07-11T04:08:34.587 回答