Lavesh J. C. Lavesh J. C. - 2 months ago 21
Vb.net Question

Parallel Loop & Stringbuilder

Intro: Hi all this is my first question, so please do let me know if I did or am doing anything wrong. I working on a project and one of its functions is to write a huge chunk of text to process the data and replace specific text at certain lines and output the file to a richtextbox/file.

Problem: The problem is that when I use a parallel foreach, my results in the richtextbox are all over the place, they are not according to lines (e.g. the first line may become the 15th line after the parallel foreach loop is run).

What the code does: It loops through a richtextbox and checks if the line matches the first line in a temporary richtextbox, if so it would stop the append and copy the text from the temporary richtextbox and let the loop run until the amount of lines which have past match the number of lines in the temporary richtextbox and then continue the append. It is basically a replace of text. Total output I am looking at about 20K lines.

Dim completertb4text As New StringBuilder("")

Parallel.ForEach(newrtb.Lines, Function() New StringBuilder(), Function(x, [option], sb)

If x.Contains(richtextboxl0) Then
startcount = True
sb.Append(vbNewLine & richtextbox3text & "111111")
End If

If startcount = True Then
If counter = temptextbox3count Then
startcount = False
Else
counter += 1
End If
End If

If sb.Length = 0 Then
sb.Append(vbNewLine & x & "222222")
End If

If sb.Length > 0 Then
sb.Append(vbNewLine & x & "3333333")
End If
Return sb

Function, Sub(sb)
SyncLock completertb4text
completertb4text.Append(sb.ToString())
End SyncLock
End Sub


Any help is kindly appreciated, thanks in advance!

Answer

Here is how I shrank my code from 08:00 seconds to 00:01 seconds.

            Dim counter As Integer = 0
        Dim countertrue As Integer = 0
        Dim countintertal As Integer = 0


        Dim newrtbstrarray As String() = newrtb.Lines
        Dim rtb3array As String() = richtextbox3text.Lines

        For Each line As String In newrtbstrarray

            If line.Contains(richtextboxl0) Then
                countertrue = counter
                For Each element As String In rtb3array
                    newrtbstrarray(countertrue) = rtb3array(countintertal)
                    countertrue += 1
                    countintertal += 1
                Next

            End If

            counter += 1
        Next
Comments