Click here to Skip to main content
15,900,649 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hi all,
If I have something like the code below:
while(true)
{
BlaBla MyInstance = new BlaBla();

//do something with this instance...
}


Will the GC dispose "MyInstance" of previous iterations of the loop, or there will be a memory crash?
Posted

Don't worry, GC takes care about it. The rule is: when the reference becomes inaccessible, the object will be collected... sooner or later. It is not possible to cause a memory leak in this way.

Nevertheless, memory leaks in .NET are quite possible even without unmanaged code, but those leaks are by design. For example, you you have an auxillary container used to accelerate search or something (like dictionary) and forget clean it when you clean your main container or data containing control.

—SA
 
Share this answer
 
Comments
Espen Harlinn 24-Feb-11 3:56am    
Good reply :)
Sergey Alexandrovich Kryukov 24-Feb-11 3:59am    
Thank you.
--SA
A new instance will be created at the beginning of each iteration. The old instance will be available for garbage collection once the new instance is assigned to the variable. It's a bit like this scenario:
C#
// First instance.
BlaBla MyInstance = new BlaBla("First Instance");
// As soon as this is assigned, the first instance will be available for garbage collection.
MyInstance = new BlaBla("Second Instance");
// As soon as this is assigned, the second instance will be available for garbage collection.
MyInstance = new BlaBla("Third Instance");
// As soon as this is assigned, the third instance will be available for garbage collection.
MyInstance = new BlaBla("Fourth Instance");
MyInstance = null;
// The fourth instance is now available for garbage collection.

Each new assignment makes the previous instance no longer referenced. Once an instance is no longer referenced, it is available for garbage collection. Basically, you shouldn't come across any memory problems.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Feb-11 15:18pm    
This is correct, 5. It should also give an idea what happens in loop, just by some logical thinking.
--SA
I think you may be a tad confused with the answers you got here specially since there's been some arguing in the comments. SA is right, garbage collection and the Dispose pattern are two different things. That said, if you are doing this in a loop, and your object is an IDisposable type with non trivial dispose-requirements, you absolute must call Dispose (or use the using-block) inside the loop. Once again this is independent of GC but something you need to do.

Now, if your class is not an IDisposable but is a type that involves non-trivial initialization, it may be a good idea to redesign the class so that you can create just a single instance, and then reuse it. As an example, if you are appending to a file in a loop, it does not make any sense to open the file, write to it, and close it in each iteration. Open it once outside the loop, do the writes in the loop and close it once you exit the loop. I just used that as an example, your scenario may not be similar.

But the mere fact that you were concerned about memory piling up set off a signal that perhaps the class you are creating may not be a light type, which is why I thought I'd throw in my 2 cents.
 
Share this answer
 
v3
Comments
Espen Harlinn 24-Feb-11 3:59am    
That's more than 2 cents - good reply, things well worth taking into consideration :)
Sergey Alexandrovich Kryukov 24-Feb-11 4:02am    
Great! If now somebody is still not getting the idea, I would not know what else to say... :-)
5,
--SA
Member 7699400 24-Feb-11 4:17am    
Thank you for your help,
since MyInstance doesn't use unmanaged code, I didn't make it IDesposeble, so I guess it's OK to leave it like it is, and let the GC to clean the previous instances.
You can use the "using" syntax. Take a look at this solution:

C#
while (true)
{
     using(BlaBla myInstance = new BlaBla())
     {
          // do something with this instance
     }
}


"using" calls Dispose() when execution is out of the "using" block. "using" is better because it guarantees the execution of Dispose(), no matter if an exception occurs. "using" is translated to a try-finally block and Dispose() is called in the finally block.

I hope it helps.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 23-Feb-11 14:37pm    
You're mixing up different things: "using" deal with IDisposable.Dispose() which can do anything. It does not mean garbage collecting at all.
--SA
fgoldenstein 23-Feb-11 14:58pm    
I agree that Dispose() is not calling the GC but it's disposing any resource you need to get disposed. Calling GC is not a solution because even when you call it, it doesn't mean it's going to run. It runs when GC thinks it's time to run. My solution releases attached resources but it doesn't clean the object from memory.
Anyway, how many instances of a class should you create in order to fill the memory? I think that using the "using" block you can be sure that no memory leak or dead lock will occur. I think that the GC is going to be smart enough to run when the memory is almost full.
Espen Harlinn 24-Feb-11 3:55am    
I've used a similar approach when dealing very large database tables - it's a workable approach
Both parts of your last sentence are possible.

The GC will deal with previous instances of BlaBla, provided there are no references to them from elsewhere in your code,
Because it cannot be determined when GC will occur it is possible that there could be memory problems.

To help the GC, BlaBla should implement IDisposable and then
C#
BlaBla MyInstance = null;
while(true)
{
  if (MyInstance != null)
  {
    MyInstance.Dispose();
  }
  MyInstance = new BlaBla();

  //do something with this instance...
}


Here are links to a two part article on GC from MSDN Magazine
Part 1[^]
Part 2[^]
 
Share this answer
 
v2
Comments
Olivier Levrey 23-Feb-11 12:25pm    
My 5. I just moved the local variable out of the loop so the test is possible.
Henry Minute 23-Feb-11 12:49pm    
Thanks Oliver. I hate coding in the CP editor.

I'm sure I wouldn't have made that mistake in VS. :sheepish-grin:
Sergey Alexandrovich Kryukov 23-Feb-11 14:39pm    
Sorry, IDisposable.Dispose() can do anything. It does not mean garbage collecting at all.
--SA
Henry Minute 23-Feb-11 20:34pm    
From the second link in my reply.
"I explained how the developer must still explicitly handle resource management and cleanup by implementing Finalize, Close, and/or Dispose methods."
Espen Harlinn 24-Feb-11 4:00am    
Good links - those article are well worth reading :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900