Click here to Skip to main content
15,880,972 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
If we call Dispose mehtod explicitly, will it invoke Garbage collector(GC)?

or
when we use using block, Is it(GC) called at the end of the block?

C#
using(StreamWriter sw=File.CreateText(@"D:\fs.txt"))
          {
              sw.Write("writing using stream writer\r\n");
          }
Posted
Comments
[no name] 25-Jul-15 1:41am    
No and no. GC runs when it needs to.
Sergey Alexandrovich Kryukov 25-Jul-15 2:13am    
Right. I answered in detail and credited your comment.
—SA

1 solution

No, it does not. The using statement uses System.IDisposeable:
https://msdn.microsoft.com/en-us/library/Aa664736%28v=VS.71%29.aspx[^],
https://msdn.microsoft.com/en-us/library/yh598w02.aspx[^],
https://msdn.microsoft.com/en-us/library/system.idisposable.aspx[^].

This interface is used as the way to perform any clean-up action in controlled manner, in contrast to GC. It is often used to release any unmanaged resource, but can be used for anything. In particular, I/O objects use it to flush the buffer and close handles. There are many other users.

As to GC, all managed memory is reclaimed based on such criterion as reachability and objects via references. This criterion is much more complicated that one could think. Please see: http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)[^].

See also the comment to the question by Wes Aday. The application cannot control when garbage collection takes place. You abandon the object by having no references to it. At the same time, if, for example, 3 objects reference each other in cycle and there are no more references, they will be reclaimed anyway. It happens some time later, which you cannot control. And when it happens, object's destructor is called. This is the reason why destructors are written quite rarely; this technique can be used only if other of calling destructors and timing is absolutely non-critical.

—SA
 
Share this answer
 
v3
Comments
utkarsharaut 27-Jul-15 6:47am    
So conclusion is disposing an object explicitlly or using dispose block will not affect GC routine.
Sergey Alexandrovich Kryukov 27-Jul-15 10:20am    
Not exactly. Most objects don't need disposing. You can consider disposing and destruction as two unrelated things.
GC is affected by reachability.
—SA

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