16 July 2016

beware of static members while disposing the class object

When static members will be used in class design

Static members in a class are used when there is need to maintain data common to all instance objects of the class. We all aware of this.

Let's understand the problem

If such static members implement IDisposable interface, then you need to pay special attention while disposing the objects of the class. If you dispose static members just similar to instance class members as part the Dispose() method implementation, you will end up in inconsistent behavior.

As static members doesn’t belong to individual class objects alone, we shouldn’t be disposing static members while disposing off the class instance members.

Consider the below a sample class, which is holding static IDisposable interface.

public class SampleClass:IDisposable
{
  public static IDisposable serviceProvider = null;
  public void Process()
  {
  //Initialize serviceProvider when 
  // required based on the bussiness logic condition
  serviceProvider = new  ConcreteServiceProvider();
  }
    
  public void  Dispose()
  {
   serviceProvider.Dispose(); // WRONG

   // Do not dispose serviceProvider as part of 
   // the SampleClass dispose.
   // When you have got mutiple SampleClass 
   // instances in application,
   // one instance got diposed off
   // then it will dispose the serviceProvider 
   // static variable. 
   // Later other instances expecting valid value
   // on serviceProvider static variable
   // will behave incorrectly.
   }
}

Why must not dispose static member is Dispose method

In the above sample class, the Dispose() method is disposing off the static member of the class. That means, whenever you create new instance of the class again, you will end up creating new instance of the static member, but that isn't a desired behavior expected. Hence pay a special attention in your Dispose() method implementation not to dispose off the static members.

Then where and when to dispose off the static members of the class?

The best place to dispose off static members is your application Exit() method. Post that you will not be needing the static members to be available for use.

No comments:

Post a Comment