What's the difference between dispose() and GC.collect()

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I use webBrowser to open a Word document,
when I use this.webBrowser.dispose(), the WinWord Process end.
while I use this.webBrowser = null, GC.Collect() , the WinWord Process
still alive.
I want to ask what's the difference between them.

ThankYou
 
George Shui said:
I use webBrowser to open a Word document,
when I use this.webBrowser.dispose(), the WinWord Process end.
while I use this.webBrowser = null, GC.Collect() , the WinWord Process
still alive.
I want to ask what's the difference between them.

Dispose for objects which implement IDisposable disposes of any managed
and unmanaged resources used by the object in a deterministic manner.

GC.Collect() forces a collection of all objects which no longer have any
references to them. If call GC.WaitForPendingFinalizers() directly
after, hopefully it will also dispose (via finalization) of all
unmanaged resources used by objects which no longer have references to
them - but there's no guarantee, just a best effort.

If your webBrowser object has a different reference from somewhere else
(say in the "children" collection of its parent, or from somewhere
else), then it won't be finalized by the collector, because it is still
alive - it still has references to it.

You should prefer calling .Dispose / .Close / 'using' in C# for all
objects which support it to relying on the garbage collector. The GC is
designed for memory, not general resources. In this case, COM embedding
of Winword is an unmanaged resource owned via the web browser control.

-- Barry
 
George

The difference between them is the same as in an analogy the difference
between a car and a road.

The Garbage collector tries to finalize all objects that are given to him in
whatever way.
"Tries" because if there is by instance a valid reference from or too that,
it won't do that.

The dispose, gives objects to the GC, as you see above does that not mean
forever that it is finalized.

Be aware that in many methods the dispose is just inherited from a parent
class the same as background is in the picturebox.

Cor
 
Back
Top