Interesting uses of IDisposable

Everyone knows IDisposable interface, right? Right. It is simple. If you use unmanaged resources, you should implement IDisposable and release them when your object is being disposed. Simple. But IDisposable is a very special interface. It even has its own keyword: using. Example use:

Code above is equal to:

Constructor is called first, then we are doing something inside, and at the end Dispose method is called to finalize work.

So maybe we could use IDisposable not only to clean up unmanaged resources, but as a shorter form of try / finally to put our code in specific context. That sounds like a great idea and obviously it is not mine. This idea was used in few places in .NET libraries. Here are 4 examples of IDisposable:


First example. This is code from ASP.NET MVC to generate HTML form using Razor:

Output of this code will be close to:

What happens? Html.BeginForm() is a function that writes "<form>" to response and returns MvcForm type object. MvcForm type implements IDisposable and its Dispose method writes "</form>" to HTTP response. We have no unmanaged resources here. We just used mechanism. Using is doing something at the beginning and something at the end and we used it to generate start and end tags of HTML form. Nice.


Next example. There is a class called TransactionScope to build transaction blocks. Here is the example usage:

What do we have here? Using block creates transaction. Some work is done inside, and then we call scope.Complete() to finish. This guarantees that whole operation is atomic.

Really simple. Where is magic here? Code inside transaction may fail and when it happens, everything needs to be cleaned up. That is where Dispose method comes in. Because it is always called, it can check if everything went right and if it didn't, it can rollback and clean up operations done in scope. One using block does a lot of work.


IDisposable can also be used to change current culture. Sometime we need to change culture for a moment, for example when we generate e-mail. This class handles it nicely:

Usage:


We can also use IDisposable to calculate time:

To calculate time and write it to console:

So as You can see, using can make our code more elegant and introduce useful features.

Komentarze

Popularne posty z tego bloga

Opinie na temat hostingu linuxpl.com

Validation using ASP.NET MVC + Kendo UI + jquery validate unobtrusive

Praca ze zdalnym kodem za pomocą PhpStorm