I have a loop of code that I want to execute, but I want each pass to be its own thread so the execution is quick. Within this pass I have several GUI items. Heres what I have tried:
sub somesub()
Dim w As WaitCallback = New WaitCallback(AddressOf WorkerDoWork)
for 1 to 10
ThreadPool.QueueUserWorkItem(w, i)
next
end sub
sub WorkerDoWork(i as integer)
dim x as string = drpitem.Selecteditem
end sub
I have also tried:
sub somesub()
Dim threads As New List(Of Thread)()
for 1 to 10
threads.Add(New Thread(New ParameterizedThreadStart(AddressOf WorkerDoWork)))
threads(i).Start()
next
end sub
sub WorkerDoWork(i as integer)
dim x as string = drpitem.Selecteditem
end sub
both error on drpitem about crossthreading. How can I do a dynamic multithreaded loop without erroring out. Also something interesting to note, is I can use background workers in the GUI successfully without erroring, but I don't know how to use background workers dynamically.
Edit:
After reading your suggestion marco, I have came up with the answer
sub somesub()
Dim w As WaitCallback = New WaitCallback(AddressOf WorkerDoWork)
for 1 to 10
ThreadPool.QueueUserWorkItem(w, i)
next
end sub
sub WorkerDoWork(i as integer)
dim x as string
invoke(sub() x = drpitem.Selecteditem)
end sub
The key is to use invoke where it breaks and it will work.