Archive for November, 2009

Testing WP LaTeX

No Comments »
   \xymatrix{ 0 \ar[r] & Z_{n+1} \ar[r]^i \ar[d]^0 & C_{n+1} \ar[r]^\partial \ar[d]^\partial & B_n \ar[r] \ar[d]^0 & 0 \\ 0 \ar[r] & Z_{n} \ar[r]^i & C_n \ar[r]^\partial & B_{n-1} \ar[r] & 0}

I guess the WP LaTeX server doesn’t have the xy package installed.


Talking about SaaS on Mr. Frost’s Podcast

No Comments »

Today I had the privilege to feature as a guest on Mr. Frost’s Podcast, a show hosted by Microsoft Developer Evangelist Daniel Melgaard Frost. The topic of the day was Software as a Service (SaaS), but the discussion digressed into areas such as EnergyMap.dk, dependency injection and ASP.NET MVC.

The podcast will be available on Daniel’s blog sometime in the future.


IDisposable, finalizers and garbage collection

No Comments »

Proper resource management in .NET requires that you understand a few basic concepts, which I will discuss in this posting.

The main resource consumed by your .NET program is memory and this consumption comes in two flavours: memory consumed by the stack and memory consumed by the heap. The stack is where local variables of primitive types are stored, while complex objects are stored on the heap.

In addition to memory your application will probably claim other system resources as well, such as file handles.

Since the amount available of any resource is constrained, its usage has to be managed. What this means is not only that we need to create or claim resources whenever we want to use them, we also need to destroy or release the resources when we are done with them. This last point, to which many textbooks do not dedicate enough attention IMO, is the tricky bit.

Because .NET is a garbage collected environment, you usually do not have to think about managing memory: memory used by local variables is managed automatically as the stack grows and shrinks during program execution. Memory allocated on the heap is managed by the .NET framework’s garbage collector. This is a component of the .NET runtime which will periodically freeze program execution, take a look at the memory allocated on the heap, compare it with the set of references currently used by your program, and release memory to which no references exist.

.NET offers (at least) two means to help you manage resources not handled by the garbage collector: the IDisposable interface and object finalizers.

Finalizers

Every .NET object has a Finalize() method. This method is called by the .NET runtime when the garbage collector collects the object. The Finalize() method should be overridden in any class which needs to release unmanaged resources prior to its destruction. However, in C# you cannot directly implement the Finalize method. That is, the compiler will not allow this:

protected override void Finalize()
{
    //Do clean up, releasing resources etc.
}

Instead you must implement a destructor. A destructor is implemented by creating a method whose name is constructed by prefixing the type’s name with a tilde (~). Thus, to create a destructor for the class MyClass, you would write this:

~MyClass()
{
    //Do clean up, releasing resources etc.
}

The C# compiler will transform this into

protected override void Finalize()
{
    try
    {
        //Do clean up, releasing resources etc.
    }
    finally
    {
        base.Finalize();
    }
}

Thus, the point of forcing you to use a destructor instead of overriding Finalize() directly is to help you remember to call base.Finalize(). Notice that it is the responsibility of the .NET runtime to call your destructor. In fact, you are not allowed to call the destructor yourself.

IDisposable

You can’t predict when the garbage collector runs (unless you explicitly force it to run). Thus, the destructor of an object may run long after your application is done with the object. For objects using scarce resources this is not desirable behaviour: you will usually want to perform clean up as soon as you are done with the object. The IDisposable interface is a means to this end.

The IDisposable interface contains a single method:

// Summary:
//     Defines a method to release allocated resources.
[ComVisible(true)]
public interface IDisposable
{
    // Summary:
    //     Performs application-defined tasks associated with freeing, releasing, or
    //     resetting unmanaged resources.
    void Dispose();
}

In this method you are encouraged to put the code which should run to release the resources the current object is holding. By implementing IDisposable you are signaling to users of your class that it uses unmanaged resources and that they should call Dispose() as soon as they are done with an instance of the class to release these resources. Moreover, implementing IDisposable does give you some benefits:

When your class implements IDisposable, the C# compiler will let you create an object of the given type in a using statement, and the .NET framework will make sure to call Dispose() when control leaves the statement:

using (MyDisposableClass m = new MyDisposableClass())
{
    //yada yada yada
}//m.Dispose() will be called here.

By calling Dispose implicitly like this, you make sure that you do not forget to call Dispose() or accidentally remove the call when reorganizing the code.

Now, how does destructors and Dispose() relate? Obviously you don’t want to have to duplicate clean up code in your class, so where should you put it: in the destructor or in Dispose()? Since Dispose() is the more aggressive approach and you aren’t allowed to call a destructor directly, you should put your clean up code in Dispose() and call Dispose() from your destructor. Be aware that putting a call to Dispose() inside your destructor means that your Dispose() method may be called multiple times: first when control leaves a using statement in which the object is being used and then again when the garbage collector collects the object and the destructor is called. Thus, your Dispose() method should not blow up if it is called multiple times. Also, Microsoft specifically declares that you should not make any assumptions on the order in which objects are collected or have their Finalize method called. Thus, when your cleanup code is called because of a call to Finalize(), you should not reference other managed resources, since these may already have been destroyed.

Suppressing Finalize

Executing a Finalize method can be costly and it actually delays the reclaiming of the memory used by the object. Thus, if appropriate clean up has already been performed for an instance through a call to Dispose(), it is desirable that the destructor is not run when the instance is collected by the garbage collector. To achieve this, your Dispose method should call the GC.SuppressFinalize() method, passing in the instance as a parameter.

That’s it. I hope this has cleared up some of the confusion usually surrounding IDisposable, finalizers and garbage collection.

As you can see, there are a number of rules you should adhere to if you want to manage resources effectively. To help you to arrive at a correct resource management scheme, Microsoft provides a reference implementation here: http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx. Notice how the Dispose(bool disposing) overload is used to ensure that only unmanaged resources are accessed when Finalize causes a dispose.