Question multithread on a list of items

soldoni

New member
Joined
Sep 24, 2012
Messages
4
Programming Experience
10+
I have a list of items in a datagrid

item1
item2
item3
item4
item5
item6
item7
etc...

I need to call a function on every item like this

function MyFunction(item from list)
but this function need some minutes (about 1-2 minutes) to be completed (because use http request etc...)

So now how I can start a multithreading on the list like this


example set a number of threads to 3 and start
MyFunction(item1 from list)
MyFunction(item2 from list)
MyFunction(item3 from list)
at the same time
when completed start
MyFunction(item4 from list)
MyFunction(item5 from list)
MyFunction(item6 from list)
at the same time
etc...
 
        Dim t As New Tasks.Task(Sub(item As Object) MsgBox(item), "hello task")
        t.Start()
 
You can create many tasks, when you start them they all run in parallell and is scheduled for the Threadpool.
 
Here's another example using Parallell.ForEach, that may run the actions in parallell. Also note you should not call this directly on UI thread, as it may use that thread. This example creates and runs a Task that call the ForEach:
        Dim items = {"A", "B", "C"}
        Tasks.Task.Factory.StartNew(Sub() Tasks.Parallel.ForEach(items, Sub(item) MsgBox(item)))
 
I tried this, but some items are skipped... why?

VB.NET:
Imports System.Threading

Public Class Form1
    
    
    Dim count, itemlist As Integer
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim tx As Thread
        tx = New Thread(AddressOf Me.StartTheProgram)
        tx.Start()
       
    End Sub
     
    Sub StartTheProgram()
        While count < 99
            For tt = 0 To 3 ' number of parallel tasks


                Dim t(tt) As Thread
                t(tt) = New Thread(AddressOf Me.MyComplicatedSub)
                t(tt).Start()
                count = count + 1
            Next
        End While
    End Sub
    Sub MyComplicatedSub()
        itemlist = count

        If itemlist > ListBox1.Items.Count Then Exit Sub
        Thread.SpinWait(80000000) 'simulate hard processing example http request etc.
        ListBox1.Items.Item(itemlist) = "Completed"
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CheckForIllegalCrossThreadCalls = False
        For i = 0 To 100 ' populating listbox with some items
            ListBox1.Items.Add("gsddsf: " & i)
        Next
    End Sub
End Class
 
Back
Top