.NET thread dies whenever object is disposed - c#

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.

Related

c# Thread Lifetime and Disposal

I have a program in which even though the call stack has been processed fully it shows <Not Available> (like this). So I started debugging froze all other threads and ran the thread completely to find out that with an empty call stack it remained there and showed <Not Available> in the thread window of Visual Studio.
So my first question, what exactly is the lifetime of a managed thread (not thread object which is processed by Garbage Collection)?
My second question is how can I get this thread to be destroyed (AKA to garbage collection for objects). Tried GC.collect(), but apparently the garbage collector doesn't process CLR implemented managed threads.
Note I have gone through
Thread Object Lifetime( <- Thread Object, not thread), and
Killing Thread ( <- Killing or terminating a running thread, I am interested for an already finished thread, with an empty call stack), and a number of similar others...
Thanks !!
This is with regard to normal threads and not worker threads taken from the threadpool.
Update- I added a thread sleep to main thread and then added a breakpoint after that to find that the threads had been destroyed now.... I want to know how this is working.

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.

stopping and removing thread after completing of task in .net

I have developed one window application in C# where i am creating one thread to perform one schedule event. now this application will run the whole day and it will create one thread for each execution of each event. How to remove threads from memory after task assigned to that thread is completed. I dont want to restrict number of threads creation by using thread pool and assigning it a specific count for max thread.
As soon as a thread finishes its execution, it will no longer consume memory and it will be targeted for the garbage collector to collect it. Thus, you don't need to worry about it. However if you are using Task, it is a good practice to Dispose it when it finishes its execution. The Task is IDisposable object.

C# Managed Thread Cleanup

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

Categories