Have you ever wondered how applications know how much memory to use, how is that memory distributed or who cleans up memory? All those operations are executed by the Garbage Collector.

What triggers Garbage collector?

  • Your system is low on physical memory.  Meaning your system has used up almost all of your RAM memory and will start to use page file.
  • The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
  • Application is written to call the GC.Collect method.

.Net framework needs your help with memory, database and network connections. If we do not dispose of connections we are going to run into several problems:

  1. If for example we are using a file in our application, another instance or user or similar scenario, will not be able to access our file use it or write to it.
  2. When connecting to a database or network location, we should always dispose of our connection as soon as we finish using that connection, because number of connections to a remote server is not infinite, meaning, we are reducing number of possible simultaneous interactions with a server.

Managed and Unamanaged code/resources

Unmanaged code is directly compiled to machine code and managed code is compiled to IL(intermediate language). Managed code is handled by .Net Framework but unmanaged code is not, there for it is dangerous to yours and others machines.

Unamanaged resources are all those resources that reside out of .Net framework, such as files, memory, database and network connections, or any other scenario outside .Net code.

What happens I do not dispose of connection of a resource?

  1. Sometimes nothing because Garbage collector will take care of objects, but it is too risky because we do not know when will that event occur.
  2. OutOfMemoryException exception will occur if Garbage Collector does not free resources because object retains references to resources. In this scenario OutOfMemoryException is thrown before application closes.

Example of implementing using IDisposable and using statement

Lets start by adding a few lined to our text file.

Error is thrown because there is still opened connection to a file on location d:\test.txt

Lets fix it.

What if we wanted to reuse first StreamWriter instance?

This is tiresome. Is there an easier way to dispose of our connections?

Yes there is, and have mentioned it in previous post. Using statement!

Adios using Dispose method 🙂

Unless you need to have custom logic added while disposing of your resources. IDisposable will be back in next post.