Reputation: 51
I have a class ClassA
public class ClassA
{
public ClassA()
{
Thread t = new Thread(EndlessLoop);
t.IsBackground = True;
t.Start();
}
private void EndlessLoop()
{
while (True)
{
// do something
}
}
}
and I'm not sure if the thread will be disposed if I set ClassA object to null
ClassA a = new ClassA();
# will the thread exit ?
a = null;
Or maybe I should implement IDisposable, and call it manually?
Upvotes: 3
Views: 965
Reputation: 100527
Nothing going to happen to the OS thread if you remove last refence to the Thread
object corresponding to it - C# Thread object lifetime. The thread will continue to run the code until the method finishes (unlikely in while(true)
case shown), thread is terminated with Abort
(don't do that - What's wrong with using Thread.Abort()) or process ends.
The only good option is to somehow notify thread's code that it should finish (i.e. using events or even global variable protected by lock
). Also consider if using Task
and async
with corresponding cancellation mechanism would simplify code (it would not solve infinite loop issue but give good framework to write cancellable operations).
Note that you can't "dispose" thread because it does not implement Dispose (Do we need to dispose or terminate a thread in C# after usage?),
Upvotes: 4
Reputation: 1960
Once started, the thread will terminate after the routine comes to an end (or Thread.Abort
is invoked or the program exits). The Thread
class doesn't implement IDisposable
so there's no Dispose
method to call. To terminate a long-running thread, you could set a flag that the thread checks periodically.
The Thread
object is eligible to be garbage collected once it goes out of scope and is no longer referenced. However, the spawned thread will continue running.
Upvotes: 5