Question

I have a project where i generate data and number it (1 - 500) by using many threads and place it inside a Label which i then place inside a grid which i then place inside a WrapPanel.

The Problem. Some of the data in threads finish before others. So my Wrap panel gets the numbers like 3 1 5 6 10 2 4 7 8 9. I want to sort the warp panel after all the threads have finished so they look like 1 2 3 4 5 6 7 8 9 10

Private Sub StartSearch_MouseLeftButtonUp
    Dim t As New Thread(AddressOf SearchBegin)
    t.Start(Data)
End Sub

Sub SearchBegin(Data)
    Dim Max = 10
    Dim Count = 1
    While Count < Max
        Dim t As New Thread(AddressOf Check)
        t.Start(Data)
        count += 1
    End While
End Sub

Sub Check(Data)
    'things happen here
    Dim display As New Action(Of Object)(AddressOf Progress)
    WrapPanel1.Dispatcher.BeginInvoke(display, Data)
End Sub

Sub Progress(Data)
    Dim g As New Grid
    'Pretty Up Grid
    Dim l As New Label
    'Pretty Up Label
    l.Content = Data.tostring
    g.Children.Add(l)
    WrapPanel1.Children.Add(g)
End Sub
Was it helpful?

Solution

Use Barrier.

To wait for all threads to be completed, define a global barrier:

Dim barr As New Threading.Barrier(1)

Add participant before starting threads:

Sub startathread()
    barr.AddParticipant()
    Dim t As New Threading.Thread(AddressOf blabla)
    t.Start()
End Sub

As the job is done, signal that it is done:

 Sub blabla()
    'do stuff
    barr.SignalAndWait()
 End Sub

Now the function starting all threads and waiting for all to be completed:

Sub x()
    For i = 0 To 9
        startathread()
    Next
    barr.SignalAndWait()
    'from this line on, all the threads are completed their jobs.
End Sub

For sorting, your thread must add each data to a list:

Dim datalist As New List(Of String)

Sub Progress(Data)
    datalist.Add(Data.ToString)
End Sub

When addition of all data is done a function to sort and place them must be called:

Sub SortAndPlace()
    datalist.Sort()

    For Each sdata In datalist
        Dim g As New Grid
        'Pretty Up Grid
        Dim l As New Label
        'Pretty Up Label
        l.Content = sdata
        g.Children.Add(l)
        WrapPanel1.Children.Add(g)
    Next
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top