Monitoring Multiple Threads

  • Thread starter Thread starter Jerry Spence1
  • Start date Start date
J

Jerry Spence1

I am starting a number of threads as follows:

For n = 1 To 10
Dim t As New Thread(New ThreadStart(MyProcedure))
t.Name = "Thread " & Trim(Str(n))
t.Start()
Next n

I have a timer that, everytime it fired needs to check that all my threads
are running. I am having difficulties using the t.IsAlive property because
't' is not unique to one thread. I feel I need something like
't.name("Thread1").IsAlive'. In other words, "Is thread "Thread1" still
alive?

How can I get a unique reference to each thread that I can then use?

Thanks

-Jerry
 
What you need is something that holds the reference to each array that you
create. Try a hashtable:

WARNING: The following code is off the top of my head and it is late,..
Might not compile 100% without a bit of tweaking....

Dim threadList as New HashTable


For n = 1 To 10
Dim t As New Thread(New ThreadStart(MyProcedure))
t.Name = "Thread " & Trim(Str(n))
t.Start()
threadList.Add(t.Name, t)

Next n

Now, you should be able to do something like:

Dim isAlive as Boolean

isAlive = DirectCast(threadList.Item("Thread1"), System.Thread).IsAlive
 
Thanks Ray. Actually I tried this with a collection as follows:


Public runningThreads As New Collection

Dim t As New Thread(New ThreadStart(AddressOf MyProcedure))
t.Name = "ReaderThread" & Trim(Str(n))
t.Start()
runningThreads.Add(t)


Then in my Timer:

For Each t In runningThreads
If t.ThreadState = Threading.ThreadState.Stopped Then
Dim t1 As New Thread(New ThreadStart(MyProcedure))
t1.Name = t.Name
runningThreads.Remove(q)
t1.Start()
runningThreads.Add(t1)
End If
Next

However, I am having a few problems with it. What is the difference between
a collection and a hashtable as far as this problem is concerned?

Thanks

-Jerry
 
The hashtable just lets you keep a reference to your object (your thread
instance in this case) indexed by another object (the thread name in my
exmaple) It lets you get the reference by the index without having to loop
through all the items to get to the one you want.

I am curious what problems you were having though...

The line you have that removes the thread if it is not running:

runningThreads.Revove(q)

....where are you getting q from?

What 'problems' were you having...
 
Thanks for that Ray - cheers

-Jerry


Ray Cassick said:
The hashtable just lets you keep a reference to your object (your thread
instance in this case) indexed by another object (the thread name in my
exmaple) It lets you get the reference by the index without having to loop
through all the items to get to the one you want.

I am curious what problems you were having though...

The line you have that removes the thread if it is not running:

runningThreads.Revove(q)

...where are you getting q from?

What 'problems' were you having...
 
Back
Top