how to make this loop multi threaded or parallel for each

I am followng for each loop basically line by line gets the MD5 hash and write to the file ... I want to make it multi-threaded... how is that possible?

 For Each line As String In lines            
file.Write(MD5(line, 2))
            file.Write("@")
            file.WriteLine(line)

           ProgressBar1.Value += 1
            'Label10.Text = MD5(line, 2)

         Next

Open in new window

LVL 5
CalmSoulAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jacques Bourgeois (James Burger)PresidentCommented:
Why do you want to do that?

Multi-threading would not make it faster, and you could eventually end up so that the lines are not written in the order that you want to write them, because threads are not sequential by their own nature.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CalmSoulAuthor Commented:
will it be possible to add error handling to this ...?
AndyAinscowFreelance programmer / ConsultantCommented:
By multi-threaded do you mean you want to put ALL of that code into another thread so your user interface updates as that file writing progresses?  

That is possible - see the documentation about BackgroundWorker class:
https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.110%29.aspx
for example code to perform a 'slow' action and update the user interface (as you want) during the operation.  You would just have to replace a couple of lines of code in that example with your actual code.
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

CodeCruiserCommented:
Have you tried Parallels.ForEach method? You will have to modify the code a bit so that it is not writing to file inside the loop and you will need to use locks to ensure all threads can safely write information to a single destination (collection/data table etc).

https://msdn.microsoft.com/en-us/library/dd460720%28v=vs.110%29.aspx
CalmSoulAuthor Commented:
@Code Cruiser:

I tried that ... but its writing two line in the output file .... if I have two thread .. I am not able to control them .. here is the code please help..

        Dim sNames As String() = {"A","B"}


        System.Threading.Tasks.Parallel.For(0, sNames.Count, Sub(i)

                                                                 For Each line As String In lines
                                                                     file.Write(MD5(line, 2))
                                                                     file.Write("@")
                                                                     file.WriteLine(line)
                                                                     ' i += 1

                                                                     ProgressBar1.Value += 1

                                                                 Next
                                                             End Sub)

Open in new window

AndyAinscowFreelance programmer / ConsultantCommented:
Any reason why you don't want to use my suggestion - which WILL write all the lines (2 or 2 million or 2 quadrillion....), whilst letting the user interface react to the user, in the correct order without you having to do anything about it.
CalmSoulAuthor Commented:
AndyAinscow: For me any option which works, I don't understand background worker ...

If you can modify my code and show me example... I will try it rightaway ..
AndyAinscowFreelance programmer / ConsultantCommented:
>>I don't understand background worker ...

Follow the link to the microsoft web site giving you a complete functional example of using a background worker.
Then change the example function 'backgroundWorker1_DoWork' by replacing the for loop (loops ten times with a wait of half a second, reporting to the main thread the 'progress') with your loop writing the file.
CalmSoulAuthor Commented:
Andy:

I have modified the code - please let me know if I arranged it correctly:

Public Class Form1


    Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, _
ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        Dim i As Integer

        For i = 1 To 10
            If (worker.CancellationPending = True) Then
                e.Cancel = True
                Exit For
            Else
                Dim file As System.IO.StreamWriter
                file = My.Computer.FileSystem.OpenTextFileWriter("C:\temp\MD5.txt", True)
                Dim lines() As String = IO.File.ReadAllLines("C:\Users\xx\PATH.txt")

                For Each line As String In lines
                    file.Write(MD5(line, 2))
                    file.Write("@")
                    file.WriteLine(line)
                    ' i += 1

                    '   ProgressBar1.Value += 1

                Next

                file.Close()
                System.Threading.Thread.Sleep(500)
                worker.ReportProgress(i * 10)
            End If
        Next

    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If BackgroundWorker1.IsBusy <> True Then
            ' Start the asynchronous operation.
            BackgroundWorker1.RunWorkerAsync()
        End If



        'Label1.Text = MD5("C:\test.txt", 2)
        'Label2.Text = SHA2("C:\test.txt", "SHA256")

    End Sub

Open in new window

AndyAinscowFreelance programmer / ConsultantCommented:
Not really - you have merged your loop into the example loop instead of replacing the example loop with your loop.
The code should work, just writing your file ten times.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.