.Net / Dynamics – Handling Unmanaged Code With “Using” Block

Just wanted to share a coding tip which can help in improving the performance of .Net applications. As Dynamics custom code is build on .Net its helpful in that space as well.

In .Net we can have both unmanaged and managed code. For the sake of keeping the blog short, we will not go into difference between them however, a managed code in dot net is the one in which CLR or “Common language Runtime” automatically reclaims the memory while for unmanaged code such as “SQL Connection”, “File IO Operation” objects CLR does not automatically does that.

In Dynamics, OrganisationServiceProxy object is an unmanaged code resource.

If we are using unmanaged resources, unhandled  exceptions can be very harmful. They can lead to issues related to dangling memory, unclosed connections to file objects etc.

For example, in the above example where we have written a “Dispose” method to free up the memory. Suppose there comes a scenario, when the application throws a scenario before the “Dispose” method is called. In such scenario, the application will never have a chance to reclaim the memory occupied by the unmanaged resources.

To avoid such scenario’s C# provides us a feature of using “Using” block in our code. When we use the using block, whatever happens inside the using block, the dispose method is always called. Lets understand this with the code implementation mentioned below

using (DisposeImplementation d = new DisposeImplementation())

Review that in the above code block we are using a class “DisposeImplementation” inside the using block.

We are not explicitly nullifying the object d, to indicate the garbage collector that its no longer needed. Also we are not explicitly calling the Dispose method to free up the unmanaged resources.

However as soon as the program will go out of scope of the using block the dispose method for the unmanaged code will be called and memory will be claimed back by the compiler.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s