Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using and Garbage Collection

Hi just to clairfy if I have the following:

using (Object1) {
create Object2
}
// bookmark1

Will Object2 be destroyed at bookmark1 along with Object1? Object2 is of StringReader and Object1 is of MemoryStream.

like image 968
DavidS Avatar asked Mar 17 '09 20:03

DavidS


People also ask

What is the use of garbage collection?

Garbage collection ensures that a program does not exceed its memory quota or reach a point that it can no longer function. It also frees up developers from having to manually manage a program's memory, which, in turn, reduces the potential for memory-related bugs.

What is called garbage collection?

Garbage Collection is the process of reclaiming the runtime unused memory by destroying the unused objects. In languages like C and C++, the programmer is responsible for both the creation and destruction of objects.

When should you not use garbage collection?

One fundamental problem with garbage collection, though, is that it is difficult to estimate and manage the actual size of the working set in memory, because garbage collector can free your memory only delayedly. So, yes, when memory is restricted, garbage collection might not be a good choice.

What is garbage collection and how it works?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.


1 Answers

Neither object will be destroyed at the end of the block.

Object1 will be Disposed, a different concept; nothing will happen to Object2.

Both objects will be collected, and may be finalised, sometime later. Garbage collection is non-deterministic - you can't rely on when it will occur.

See IDisposable on MSDN for more.

like image 143
Bevan Avatar answered Sep 27 '22 23:09

Bevan