Search code examples
c#performancegarbage-collectiondispose

C# Disposable Context as Method Parameter


I have a question about IDisposable Method parameters.
Assume i have got a class which implements the IDisposable Interface, such as "TestClass":

class TestClass : IDisposable
{
   public void TestMethod()
   {
     Console.WriteLine("I am a Test Method");
   }

   public void Dispose()
   {
     Console.WriteLine("Test Method was disposed!");
   }
}

Suppose I want to put a instance of IDisposable Class (e.g. DB Context) into a method to perform context dependent actions. Usually we use this like in the following example:

static void Main(string[] args)
{
   using (var context = new TestClass())
   {
      X(context);
   }
}

public static void X(TestClass context)
{
  context.TestMethod();
}

The result is, as expected, that the Dispose() method is called. (Debugger attached, or displayed "Test Method was disposed!" on Console)

So the question is: If i will write something like this:

static void Main(string[] args)
{   
   X(new TestClass());
}

I cannot see any indicator that the Dispose method has been called? Is the TestClass() context automatically disposed of if the execution of the method was successful / finished.

Is the dispose method called when the garbage collector cleans this up? I am concerned that resource-intensive contexts will still be open?


Solution

  • The garbage collector can only clean up managed resources (things created with new). Classes that work with unmanaged resources typically implement a finalizer/destructor, that calls Dispose() for you when you haven't already. The garbage collector does call the finalizer. See here for an example and more information.

    If you don't explicitly call Dispose() and your class does not have a destructor, Dispose() won't be called at all. This shouldn't be a problem, because at that point the garbage collector is already cleaning up anyway.

    So for classes that do not own unmanaged resources, Dispose() just gives control over when resources are to be freed.