views:

52

answers:

3

I have a windows service that spawns off around 60 threads when it starts. I am using Nagios for general monitoring and I have all necessary routines to send data to nagios. However, I cannot figure out how to get a sum of all threads and make sure that none of them are dead.

Basically what I want to do is:

foreach(thread t in threadPool)
{
    if(t.isAlive())
    {
        PingHost(t.ThreadID);
    }
}

It doesn't seem like this should be very difficult, but I am not sure where to start.

+1  A: 

Just a comment, 60 is a lot of threads as a fixed number. You might want to consider a processing loop instead (even if it has its own dedicated thread) - much easier to debug and more scalable.

But if you REALLY need this, one option is to ... when the thread starts, do an interlocked increment of some shared counter. Just before the thread is finished its work, do an interlocked decrement.

uosɐſ
Unfortunately, I inherited this project and am stuck with threading. But I need more info than just a count of the threads to determine what is going on. I will need to associate the thread ID with the specific process that the thread is working on and then inform nagios if the thread is down.
Jacob Huggart
Yes, a project that has 60 threads tends to get inherited frequently. It is really rather off the deep end. Fix the real problem.
Hans Passant
+1  A: 

I recommend adding each thread to a Dictionary<int, Thread> keyed by its ManagedThreadId. Then pass a callback method to each thread that returns its ManagedThreadId when it terminates. The callback then removes the thread from the dictionary and informs Nagios.

You can use the thread's Name property for basic descriptive data, or create a custom object to hold other information about the process and store that inthe dictionary instead of the thread.

ebpower
This sounds good. I just created an object to store information about the process the thread is working on. I will give the Dictionary idea a try.
Jacob Huggart
For each new thread, I am going to create an object that contains all of the information that I need, including the ManagedThreadID. Is it possible to call thread.IsAlive based on the ManagedThreadID?
Jacob Huggart
IsAlive is a property of a thread object. Instead, include the thread in your info object.
ebpower
That is exactly what I ended up doing. Thank you!
Jacob Huggart
A: 

If you have some special needs about programming with threads, the SmartThreadPool project may please you.

controlbreak