what is the difference between finally and dispose methods?

Answer Posted / monika

The important difference is timing. Finalize is called
after the .NET garbage collector runs. That can take a
while, depending on how frequently you allocate memory and
in what generation the object lives. Dispose() is the
standardized way to free up the unmanaged resources your
object uses well before the finalizer gets a chance to do
so. A Bitmap would be a good example, it takes very few
managed resources but can eat a huge chunk of unmanaged
memory, depending on the size of the bitmap. If you don't
call Dispose on it after you're done using it, your app can
potentially consume large amounts of unused memory for an
extended amount of time.

While Finalize is called automatically, Dispose() isn't.
You must call it explicitly or you can use the V2.0 "using"
statement in VB.NET or C#. Or the "stack allocation"
syntax in C++/CLI. Using "using" is preferred, it ensures
Dispose() is called, even if there's an exception. When
Dispose() runs, you won't need the finalizer anymore so
call GC.SuppressFinalize(). That makes the finalizer
thread running a lot leaner too.

You don't have to implement Dispose() if your class doesn't
consume unmanaged resources. If it has a member that
implements Dispose(), you'll need to implement Dispose()
too so you can call that member's Dispose() method.

Is This Answer Correct ?    53 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Difference between Value type & reference types ? and give the example in .Net?

613


How does c# generics and c++ templates compare?

558


Explain namespaces in c#.

666


what is the difference between .dll and .exe

619


Write a program to create a user control with name and surname as data members and login as method and also the code to call it. (Hint use event delegates) Practical Example of Passing an Events to delegates

590






Is multiple inheritance possible in c#?

647


What is private class in c#?

569


Do loops in c#?

573


Do we get an error while executing the “finally” block in c#?

595


What is the diff between System.String and System.Text.StringBuilder classes?

615


What is tpl in c#?

580


What does f mean in c#?

592


What is regex replace in c#?

616


Is php better than c#?

580


What is the use of constructor in c# with example?

509