DCOM used a distributed pinging mechanism in conjunction with client keep-alive messages to know when server-managed components can be released. This mechanism does not scale well in practice and causes many problems in a WAN environment.
.NET remoting uses a lifetime lease model. When an object is activated, it is assigned an initial time to live. On each method invocation, the lifetime can also be extended by a specified amount. If an object is not invoked during the period of the current lease, the object is deactivated. Also, note that when a lease is extended because of a method call, the extensions are not cumulative. For example, if a lease is extended by two minutes on each method call, calling a method five times in rapid succession will not extend the lease to ten minutes. Instead, the time to live is extended to a maximum of two minutes at the end of each method call.
Sometimes, however, this lease extension model is not sufficient. For instance, you may decide to use some business logic to determine if an object's lifetime should be extended. In this case, you can associate an object's type with a type of object known as a sponsor. This sponsor object is responsible for determining whether the object's lease on life should be extended.
To override the default lease on a per-class basis, override the MarshalByRefObject::InitializeLifetimeService. The following example shows how you can do this:
private __gc class SecretPerson
: public MarshalByRefObject, public IPerson
{
public:
...
Object* InitializeLifetimeService()
{
ILease* lease = dynamic_cast<ILease*>(
MarshalByRefObject::InitializeLifetimeService());
if (lease->CurrentState == LeaseState::Initial)
{
lease->InitialLeaseTime = TimeSpan::FromMinutes(2);
lease->RenewOnCallTime = TimeSpan::FromSeconds(30);
}
return lease;
}
...
};
public __gc class PersonFactory
: public MarshalByRefObject, public IPersonFactory
{
public:
Object* InitializeLifetimeService()
{
return 0;
}
};
The code demonstrates the following concepts:
- The
SecretPerson class overrides the default timeouts. - The
PersonFactory class returns zero from the InitializeLifetimeService function to give the factory object an infinite lifetime.
This lease-based model applies to both client- and server-activated objects.
Holding a remote reference to an object does not prevent a .NET remoting object from being garbage collected. If the lease expires on the server, the server-side object reference is discarded, and the object becomes a candidate for garbage collection. The client-side transparent proxy will throw an exception when the client attempts to use the object. This is true even if the object has not yet actually been garbage collected.
Go to the next step | Go to the previous step
See Also
Managed Extensions for C++ and .NET Remoting Tutorial