_urls
will stay indefinitely because it is located in a field as it seems.DownloadTexts()
(the iterator returned by it) is kept alive until the end of the loop.- the
WebClient
and thehtml
it produces stay alive for one iteration. If you want to know the absolute precise lifetime of it, you need to use Reflector and mentally simulate where the reference travels around. You'll find that theIEnumerator
used in the loop references it until the next iteration has begun.
All objects that are not alive can be GC'ed. This happens whenever the GC thinks that is a good idea.
Regarding your Edit: The cases are equivalent. If you don't put the enumerator into a variable, the compiler will do that for you. It has to keep a reference till the end of the loop. It does not matter how many references there are. There is at least one.
Actually, the loop only requires the enumerator to be kept alive. The additional variable you added will also keep the enumerable alive. On the other hand you are not using the variable so the GC does not keep it alive.
You can test this easily:
//allocate 1TB of memory:
var items =
Enumerable.Range(0, 1024 * 1024 * 1024)
.Select(x => new string('x', 1024));
foreach (var _ in items) { } //constant memory usage