Marc Intes
Marc Intes

Reputation: 737

Program freezes when opening a textfile with over 100,000 lines

My code lets the user open a text file and the contents of the textfile per line is being placed inside an array, but my program freezes when the contents of the textfile has over 100,000 lines or more. I have tried backgroundworker but it seems not to support OpenFileDialog.

It runs fine on 1,000 lines or less, but i need over 100,000 lines of text for this program. Is there any way to tweak its performance so it won't freeze?

here is my code:

 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

Upvotes: 0

Views: 190

Answers (1)

Derek Tomes
Derek Tomes

Reputation: 4007

A backgroundWorker shouldn't have any UI in it.

What you need to do is:

  • Prompt for the filename in your main UI
  • create the stream in BackgroundWorker.DoWork
  • get rid of the array / redim array and use a StringCollection - you can convery it to an array at the end if you really want one.
  • raise any events through the BackgroundWorker.RunWorkerCompleted

Avoid redim preserve if you can, it's horrible.

Upvotes: 2

Related Questions