Ingo Rammer Technology Consulting
^ .NET Remoting FAQ
» IngoRammer.com
» My Books
» Conferences
» Consulting & Services
» Newsletter
 
 
 
» Contact
 

INFO: Why Singletons are destroyed after five minutes

Question

I have a C# class that is being exposed via remoting as a Singleton Server Activated Object.

However, sometimes this object just disappears and a new one is created. Shouldn't only a single instance ever exist for a Singleton?

Answer

Remoting uses a so called "lease based" lifetime services. When you create an object it has a certain time-to-live (normally 5 minutes) upon every methodcall you place from your client onto the object an additional time ("RenewOnCallTime", usually 2 minutes) will be added to the object's lifetime.

This is also valid for Singletons - the only difference is that the server employs a guarantee, that there either exists exactly one instance or none at all.

When you don't call the server for about 5 minutes, the object will be garbage collected. You can work around this using two schemes:

First, you can provide different leases than the default:

public class Foo : MarshalByRefObject {
  public override Object InitializeLifetimeService()
  {	
    ILease lease = (ILease)base.InitializeLifetimeService();
    if (lease.CurrentState == LeaseState.Initial)  {
      lease.InitialLeaseTime = TimeSpan.FromMinutes(100);
      lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
      lease.RenewOnCallTime = TimeSpan.FromSeconds(100);
    }
    return lease;
  }
}

This piece of code will ensure that the MarshalByRefObject will live for at least 100 minutes.

If you want your singleton to live forever, you can simply return null:

public class Foo : MarshalByRefObject 
{
  public override Object InitializeLifetimeService()
  {
    return null;
  }
}

The second way is to use different sponsor-object [on the client, the server or somewhere else]. Upon running out of lease time the .NET-Remoting framework will call the sponsor of the object an ask it, if it wants to renew or increase the lease time. The sponsor now has 2 Minutes (ILease SponsorshipTimeout) to answer this request, else the object will time-out.






© 2002, 2003 by Ingo Rammer (ingo@ingorammer.com). Information is provided as-is and is subject to heavy changes due to its pre-release character.