0

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.

Jeff Luyet
  • 424
  • 3
  • 10
  • Look here [enter link description here][1] [1]: http://stackoverflow.com/questions/17334425/vb-net-delegates-and-invoke-can-somebody-explain-these-to-me – MeTitus Aug 04 '15 at 22:52

1 Answers1

0

Problem is, you are creating a thread and then accessing an object which is being handled in another one. Have a look here:

VB.NET Delegates and Invoke - can somebody explain these to me?

Community
  • 1
  • 1
MeTitus
  • 3,390
  • 2
  • 25
  • 49