How do the ISponsor and ILease interfaces work?
Asked Answered
A

2

6

I've created a object that inherits from MarshalByRefObject and ISponsor. In my implementation of ISponsor I just return a timespan to indicate how long I want the object renewed for.

When I call InitializeLifetimeService() to get an ILease reference to be passed into my ISponsor object it never appears to be used from examples I've seen.

ISponsor just seems to return a TimeSpan without actually using the ILease reference. But I'm sure there is more going on here since remoting is involved.

How do ISponsor and ILease work, specifically in terms of object lifetime renewal?

Apiculate answered 6/9, 2012 at 18:47 Comment(0)
R
5

In parent AppDomain you obtain ILease object by either InitializeLifetimeService or GetLifetimeService call with proxy instance of object in the new AppDomain. You never need to implement ILease yourself (outside of testing your ISponsor implementation).

Than you register your custom Sponsor object which implements ISponsor with ILease.Register call and configure ILease object with timeouts.

When your Sponsor object get called with Renewal you can say how long to keep the object alive and also may adjust/display properties of passed in ILease instance.

Receiptor answered 6/9, 2012 at 19:14 Comment(0)
W
5

In a client app where you want to extend the lease of a remote object you would typically obtain an ILease interface for the object by calling

ILease lease = (ILease)RemotingServices.GetLifetimeService( remoteObject );

and then pass it your custom sponsor object

lease.Register( customSponsor );

where your custom sponsor class will look something like this:

private class CustomSponsor : MarshalByRefObject, ISponsor
{
    public TimeSpan Renewal(ILease lease)
    {
        Debug.Assert(lease.CurrentState == LeaseState.Active);
        //Renew lease by 5 minutes

        return TimeSpan.FromMinutes(5);
    }
}

For more information check out this helpful MSDN article on leasing and sponsorship. http://msdn.microsoft.com/en-us/magazine/cc300474.aspx

The link no longer works - it was in the December 2003 issue though which can be downloaded in CHM format from the same page.

A wayback machine link is here:

https://web.archive.org/web/20080906214332/http://msdn.microsoft.com/en-us/magazine/cc300474.aspx

Worldweary answered 14/8, 2014 at 18:34 Comment(2)
Thank you for the sample code. The link to the MSDN article is bad, it redirects to the MSDN home page (they must have removed the article).Topmast
@DSO Thanks for pointing that out. It was in the December 2003 issue of MSDN magazine. I've added a wayback machine link.Worldweary

© 2022 - 2024 — McMap. All rights reserved.