Assertfail

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


Comments

Do you want to send a comment or give me a hint about any issues with a blog post: Open up an issue on GitHub.

Do you want to fix an error or add a comment published on the blog? You can do a fork of this post and do a pull request on github.