Threads .NET threads whenever an object is located

I am running this code in my thread created using new Thread() . Once obj is located, the thread dies. However, thread execution should never stop due to an infinite loop:

 while (true) { using (var obj = httpWebResponse.GetResponseStream()) { // do stuff } // never gets this far, thread dies } 

Why is this happening? This is not the case if I call obj.Dispose() explicitly. Without recycling, the stream works fine and continues indefinitely.

Is the CLR counting the number of references to objects contained in the code and killing the stream when they reach zero, despite the loop?

+4
source share
2 answers

The garbage collector will collect and destroy the object as soon as there are no other references to the object. Thus, if you call a method and inside this method there is a local variable that refers to the stream, the stream will be killed as soon as (possibly later, depending on when the garbage collector runs) you leave the function. The only way to ensure that the stream continues to work is to maintain a reference to the stream. This can be done either through a static variable, or through some other variable that does not go beyond.

-2
source

The accepted answer is incorrect when it indicates

"The only way to ensure that the stream continues to work is to maintain a reference to the stream"

As pointed out by Simon and Microsoft,

"There is no need to keep a reference to the Thread object after you start the thread. The thread continues to run until the thread procedure is complete."

http://msdn.microsoft.com/en-us/library/system.threading.thread(v=vs.110).aspx

+3
source

Source: https://habr.com/ru/post/1336235/


All Articles