|
-
Sep 2nd, 2010, 12:22 PM
#1
Thread Starter
Hyperactive Member
waiting for threads?
My understanding is that thread.join will suspend the execution of code on the calling thread until the spawned thread finishes or is aborted...
With that in mind, I tried this:
Code:
For i = 1 to 50
threads = New Thread(AddressOf test)
threads.IsBackground = True
threads.SetApartmentState(ApartmentState.STA)
threads.Start(i)
next
threads.join
''''rest of code after''''
However, the rest of the code runs when the loop finishes, not waiting for all the spawned threads to finish.
Since the rest of the code needs the threads to finish (otherwise the rest will error), is there any way to accomplish this?
-
Sep 2nd, 2010, 02:15 PM
#2
Re: waiting for threads?
This is the kind of situation that the Parallel's library in VS2010 was made for. For your application though, the problem is, every loop cycle, you're changing the definition of the variable "threads", so when it exit's the loop, it's only going to wait for the LAST thread; thread #50 to Join before moving on. Like anything multithreaded, there's no guarentee what order they'll process in, so #50 could finish anywhere between first and last.
What you need to do is make an array of thread pointers:
Dim threads(49) As Threading.Thread
and assign each one to a new thread:
threads(i-1) = New Thread(AddressOf test)...
Then, when you exit the loop, make a new loop and join them all. It will run the Join tests sequentially, but it doesn't matter since you need them all to finish up.
-
Sep 2nd, 2010, 06:04 PM
#3
Thread Starter
Hyperactive Member
Re: waiting for threads?
Jenner that works out really well, but ran into something weird. Since I don't know the amount of threads created, Dim threads() as Threading.Thread won't work. It seems ok but when debugging, the app breaks at the threads(i)=New Thread(AddressOf test), saying "Object reference not set to instance of object, use "new" keyword..." So, I just used some obscure number that won't be reached, like 5,000, and now it works out.
-
Sep 2nd, 2010, 06:28 PM
#4
Re: waiting for threads?
You should be using a WaitHandle for this. I don't have time to create an example now but look up the AutoResetEvent and ManualResetEvent classes and the WaitHandle.WaitAll method.
-
Sep 2nd, 2010, 10:25 PM
#5
Re: waiting for threads?
Yea, a WaitHandle would probably be more efficient. If jmcilhinney or someone else doesn't beat me to it, I'll whip up an example tomorrow.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|