开发者

.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开发者_StackOverflow社区 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜