C# Managed Thread Cleanup - c#

After my application creates a thread using a ParameterizedThreadStart delegate, that thread performs some initialization and runs to completion. Later on, I can observe that this thread is no longer active because its IsAlive property is false and ThreadState property is ThreadState.Stopped.
Once a thread reaches this state they remain in my application, still existing as thread objects until my application shuts down. Are there any steps I can take to dispose of them once they're no longer active? I would like to delete the object and deallocate any resources so that any given moment the only thread objects I have are active threads. Thread doesn't implement IDisposable, though, so I'm not sure how I should do this.

You're holding onto the reference to the thread in your code.
If you have written code that will check the state of the thread, then that code inherently will keep the thread object alive until the GC collects it.
Once you are finished with a thread, or ideally if you don't need to access it, make sure you null all references to it. Thread doesn't implement IDisposable because as you've made clear this wouldn't make sense for a thread.
Threads are native in .Net so you don't have to worry about leaks. If you're certain they will stop then just delete them from your list once you are sure it has finished.

It sounds like you need to let go of your reference to the Thread object, so the garbage collector can discard it. Just set the reference you have to null, and let the GC do its job when it's ready.
Depending on your situation, you may wish to use a WeakReference (or my friend Cyrus' WeakReference<T>).

Is the unmanaged thread still there, did the thread actually return from its ParameterizedThreadStart method? Also try making IsBackground = false

Related

Dispatcher does not dispose on exit

I am creating a wrapper for a COM library that interacts with IBM mainframes. It can only be accessed from a single thread. To get around this, I've created a System.Windows.Threading.Dispatcher to handle running all interactions on a dedicated thread.
My problem is that if the object is not disposed explicitly, the dispatcher stays running after a WinForm application exits. The finalize method is never called for the object that creates the dispatcher. I need the sessions to be closed reliably to prevent unnecessary connections.
If I call GC.Collect on application exit, it will close fine. However, the library that I created will be used by mostly inexperienced developers. I cannot count on them always Disposing, collecting garbage or all committing to either WinForms or WPF to hook into application exit events.
I've read that if a class has a finalizer, its cleanup gets deferred until later. That may be part of the issue, but I can get around having a finalizer?
The finalize method is never called for the object that creates the dispatcher
The finalizer is called, when GC decides to perform grabage collection. You shouldn't rely on finalizer, when you need to dispose resources explicitly, because you shouldn't interfere in GC work.
I cannot count on them always Disposing
I'm afraid, you have no choice. Implement IDisposable and force your users to call Dispose. This is normal practice in .NET.
Using WPF's dispatcher in a Winforms app isn't exactly a great idea. Check this answer for the equivalent Winforms approach.
Getting the COM objects released otherwise doesn't take a great effort. Just set the thread's IsBackground property to true. Which will make the CLR automatically abort the thread when the program's main thread exits. The CLR then runs one final garbage collection, the exact equivalent of you calling GC.Collect() explicitly.

Find which thread currently owns a lock so I can kill it

I need to find out which thread currently owns the lock.
I'm writing a multithread server using ThreadPool that hosts independent application instances. When shutting down an application instance I call Monitor.TryEnter to either acquire the lock or timeout. If a timeout occurs I need to get which thread owns the lock so I can abort it.
If there are no bugs in the applications I would never need to do this as each worker would lock and unlock the application instance on entry and exit to the application. But if there IS a bug, and for whatever reason the worker doesn't exit and is either deadlocked or stuck in an endless loop I want to be able to kill that thread and application instance, while letting the rest of my server live on. The application instance at this point is a lost cause.
Seems like a pretty straight forward requirement, but couldn't find anything built in to do it.
One workaround would be to add a Thread member in the same context as the lock and have each thread update it as it acquires the lock. But that relies on everyone ALWAYS remembering to update it when a lock is acquired.
You think the thread control as a top down hierarchy, but this is not the right way of thinking in the matter of multithreaded applications. If a Thread has a timeout or something else went wrong during its execution, the thread itself has to take care of releasing the lock and ending itself.

Threads and garbage collection

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 myThread a method variable? or...?
In most scenarios, the thread will simply be garbage collected when possible. There is no need to set myThread to null if myThread is 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.
Use thread pool. Don't spawn threads by yourself and don't invent the wheel.

.NET thread dies whenever object is disposed

I'm running this code in its own thread, created using new Thread(). As soon as obj is disposed the thread dies. However, the thread execution shouldn't ever stop, because of the endless loop:
while (true)
{
using (var obj = httpWebResponse.GetResponseStream())
{
// do stuff
}
// never gets this far, thread dies
}
Why does this happen? It's no different if I call obj.Dispose() explicitly. Without disposing, the thread runs fine and continues indefinitely.
Is the CLR counting the number of object references held by the code, and killing the thread when they reach zero, despite the the loop?
The accepted answer is incorrect when it states,
"The only way to ensure the thread keeps running is to maintain a
reference to the thread"
As Simon pointed out and per Microsoft,
"It is not necessary to retain a reference to a Thread object once you
have started the thread. The thread continues to execute until the
thread procedure is complete."
http://msdn.microsoft.com/en-us/library/system.threading.thread(v=vs.110).aspx
The garbage collector will pick up and destroy the object as soon as there is no other references to the object. So, if you call a method, and inside that method there is a local variable which references the thread, the thread will be killed as soon as (possibly later, depending on when the garbage collector runs) you leave the function. The only way to ensure the thread keeps running is to maintain a reference to the thread. This can either be done through a static variable, or through some other variable that does not go out of scope.

Deterministic dispose of ThreadStatic objects

The ThreadStatic attribute declares a static variable as unique-per-thread.
Do you know an easy pattern to correctly dispose such variables?
What we used before ThreadStatic is a ThreadContextManager. Every thread was allocated a ThreadContext which retained all thread-specific information. We spawned some threads and let them work. Then, when they all finished, we disposed of the ThreadContentManager, which in turn disposed all the contexts if they were IDisposable.
I don't see an immediate way to translate this pattern to ThreadStatic objects. The objects will be disposed of eventualy, because the threads die, and so nothing reference them. However, we prefer deterministic dispose whenever possible.
Update
I do not really control the threads directly - I'm using Microsoft CCR, which has a ThreadPool that does tasks. When all the tasks are done, I'm disposing the Dispatcher (which holds the threadpool). The thing is - I do not get a chance to do anything "at the end of a thread's main function" - so I can't dispose things manually at the end of a thread's run. Can I access the thread's static objects from outside the thread somehow?
You can still use the equivalent of your ThreadContextManager class to handle the dispose. The spawned threads dispose of this 'manager' object which in turn takes out all the other thread static objects it knows about.
I prefer to have relatively few thread static objects and use a context object instead. This keeps the thread specific state in only a few places, and makes patterns like this easier.
Update: to handle the threadpool case you could create a base 'task' object that is the one that you pass to the thread pool. It can perform any generic initialization your code needs, invoke the 'real' task and then performs any cleanup needed.

Categories