I have a windows service which runs continuously and creates some threads to do some work. I want to make sure that these threads are properly disposed of (garbage collected after they are finished.
However, I also want to be able to check to see if they are alive periodically and terminate them if they are. I know I can’t keep any references to them, though, because then they wouldn’t be garbage collected.
Is there an alternative way to check for the existence/state of user-defined threads? I was thinking maybe something like the following using WeakReference: (I can’t fully test right now or I’d just test it myself)
List<WeakReference> weakReferences;
Thread myThread = new Thread(() => Foo());
WeakReference wr = new WeakReference(myThread);
weakReferences.Add(wr); //adds a reference to the thread but still allows it to be garbage collected
myThread.Start();
myThread = null; //get rid of reference so thread can be garbage collected
and then at the beginning of my onTimeElapsed event (run every 5 minutes):
foreach(WeakReference wr in weakReferences)
{
Thread target = wr.Target as Thread; //not sure if this cast is really possible
if(target.IsAlive && otherLogic)
{
target.Abort();
{
}
But I’m not sure exactly how WeakReference works. Any ideas on how to properly do this?
Is
myThreada method variable? or…?In most scenarios, the thread will simply be garbage collected when possible. There is no need to set
myThreadtonullifmyThreadis a method variable, because that won’t exist at the time.I would, however, note that threads are actually pretty expensive objects (the stack alone is a pain to allocate). If possible, I would suggest either using the
ThreadPool(if each item is short-lived), or a bespoke work queue (if longer), potentially with multiple workers servicing a single queue.As for terminating/aborting a thread… that is never a good idea; you have no idea what the thread is doing at that point. After that, it is possible that your entire process is doomed. If at all possible, consider having the worker check an “abort” flag occasionally. If not possible, consider doing the work in a separate process. A process is even more expensive than a thread, but it has the advantage that it is isolated; you can kill it without impacting yourself. Of course, you could still corrupt any files it was working on, etc…
Frankly, the main time I would ever consider aborting a thread is if my process is already dying, and I’m trying to put it out of misery ASAP.