Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on IDisposable

My question is why do I need IDisposable? I have a class that consumes some resources that need to be freed. I have two options

Without IDisposable

class SomeUtilityClass
{
 public Stop()
 {
   // free resources
 }
}

With IDisposable

    class SomeUtilityClass, IDisposable
    {
     public void Dispose()
     {
       // free resources
     }
    }

So why do I need IDisposable here? It does not matther how to name the function.

class Program
{

 public Main(..)
 {
   SomeUtilityClass _class = new SomeUtilityClass();

   // clean up when we've done

  _class.Stop();

   // OR
  _class.Dispose();

 }
}
like image 640
Captain Comic Avatar asked Dec 09 '22 13:12

Captain Comic


2 Answers

Because IDisposable is supported by C# and you can use cool using syntax:

using (IDisposable someDisposable = new ...)
{
    // your code with someDisposable 
}

This is actually transformed by compiler to something like:

IDisposable someDisposable = new ...
IDisposable someDisposable2 = someDisposable ;
try
{
    // your code with someDisposable 
}
finally
{
    if (someDisposable2 != null)
    {
        someDisposable2.Dispose();
    }
}

So if any exception happens inside using block your object would be disposed anyway.

like image 154
Andrew Bezzub Avatar answered Dec 14 '22 23:12

Andrew Bezzub


You should only really use IDisposable when your class consumes unmanaged resources, and they need to be freed immediately (streams, db etc).

It also provides a way for the CLR to 'clean up' when there are unhandled exceptions that cause your thread to be unloaded.

Calling IDisposable marks the object as being available for garbage collection immediately, but if not implemented correctly you can cause your object to be promoted a garbage collection generation which can cause memory pressure (refer to Jeffery Richters CLR via c# 3 if you want a full explanation).

a quick google turned this up: http://kleahy-technical.blogspot.com/2009/01/idisposable-and-garbage-collection.html

i suggest you read into the IDisposable pattern, when to use it, when not to and its implications on GC and state.

EDIT: there is loads of info on stackoverflow too: Use of Garbage Collection?

like image 30
TimC Avatar answered Dec 14 '22 22:12

TimC