Assertfail

All Posts assertfail

View the Blog on GitHub wallymathieu

Implementing Dispose method in .net

25 Sep 2011

Dispose

In order to release unmanaged resources you need to use or implement the dispose method.

Unmanaged resource

So what is an unmanaged resource? It is simply resources that the CLR does not manage for you. For example: File streams, database connections, P/Invoked api:s.

How to implement Dispose?

Msdn gives a rather clear answer.

When is it unsafe to call both dispose and finalize?

One reason could be that you’re dealing with a P/Invoked api. Telling the unmanaged code to clean up the resources associated with a particular pointer twice can cause unintended consequences. Using closed handles is a security risks since windows recycles handles. Another reason is performance: A finalize is costly to perform.

Alternative to using IntPtr

In order to simplify the use of operating system handles you can use “Safe Handle”.

Tags

  • c#
  • memory_management
  • Comments or errors? Fork post and do a pull request on github