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 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.