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.
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.
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.
If you have some special needs about programming with threads, the SmartThreadPool project may please you.
精彩评论