Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

RemotingServices.GetLifetimeService Method

Returns a lifetime service object that controls the lifetime policy of the specified object.

Namespace: System.Runtime.Remoting
Assembly: mscorlib (in mscorlib.dll)

public static Object GetLifetimeService (
	MarshalByRefObject obj
)
public static Object GetLifetimeService (
	MarshalByRefObject obj
)
public static function GetLifetimeService (
	obj : MarshalByRefObject
) : Object
Not applicable.

Parameters

obj

The object to obtain lifetime service for.

Return Value

The object that controls the lifetime of obj.

Exception typeCondition

SecurityException

The immediate caller does not have infrastructure permission.

For the default lifetime service the returned object will be an object of type ILease. If the obj parameter is a null reference (Nothing in Visual Basic), the method returns a null reference (Nothing in Visual Basic).

The following code example demonstrates how to use the GetLifetimeService method to get a lifetime lease for the specified object.

using System;
using System.Collections;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;
using TimerSample;

namespace GroupCoffeeTimer {
    public class TimerClient : MarshalByRefObject, ISponsor {
        public static void Main() {
            TimerClient myClient = new TimerClient();
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        public TimerClient() {
            // Registers the HTTP Channel so that this client can receive
            // events from the remote service.

            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();
            serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();

            IDictionary props = new Hashtable();
            props["port"] = 0;
            HttpChannel channel = new HttpChannel(props, clientProv, serverProv);
            ChannelServices.RegisterChannel(channel);

            WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(typeof(TimerService), "http://localhost:9000/MyService/TimerService.soap");
            RemotingConfiguration.RegisterWellKnownClientType(remoteType);
            
            TimerService groupTimer = new TimerService();
            groupTimer.MinutesToTime = 4.0; 

            // Registers this client as a lease sponsor so that it can
            // prevent the expiration of the TimerService.
            ILease leaseObject = (ILease)RemotingServices.GetLifetimeService(groupTimer);
            leaseObject.Register(this);
            
            // Subscribes to the event so that the client can receive notifications from the server.
            groupTimer.TimerExpired += new TimerExpiredEventHandler(OnTimerExpired);
            Console.WriteLine("Connected to TimerExpired event");
            
            groupTimer.Start();
            Console.WriteLine("Timer started for {0} minutes.", groupTimer.MinutesToTime);
            Console.WriteLine("Press enter to end the client process.");
            Console.ReadLine();
        }
        
        private void OnTimerExpired (object source, TimerServiceEventArgs e) {
            Console.WriteLine("TimerHelper.OnTimerExpired: {0}", e.Message);
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        public TimeSpan Renewal(ILease lease) {
            Console.WriteLine("TimerClient: Renewal called.");
            return TimeSpan.FromMinutes(0.5);
        }
    }
}

To compile and run this example, you will need to compile and run a server, timerserver.exe, and compile a shared library, timerservice.dll.

The source for timerserver.exe follows:


using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Lifetime;
using System.Timers;

namespace TimerSample {
    public class TimerServer {
        public static void Main() {

            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();
            serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();

            IDictionary props = new Hashtable();
            props["port"] = 9000;
            HttpChannel channel = new HttpChannel(props, clientProv, serverProv);
            ChannelServices.RegisterChannel(channel);
            RemotingConfiguration.RegisterWellKnownServiceType(
    									typeof(TimerService), 
    									"MyService/TimerService.soap",
    									WellKnownObjectMode.Singleton);
            
            Console.WriteLine("Press enter to end the server process.");
            Console.ReadLine();
        }
    }
}


The source for timerservice.dll follows:


using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;
using System.Timers;

namespace TimerSample {
    // Define the event arguments
    [Serializable]
    public class TimerServiceEventArgs : EventArgs {
        private string m_Message;
        public TimerServiceEventArgs(string message) {
            m_Message = message;
        }

        public string Message {
            get {
                return m_Message;
            }
        }
    }
    
    // Define the delegate for the event
    public delegate void TimerExpiredEventHandler (object sender, TimerServiceEventArgs e);

    // Define the remote service class
    public class TimerService : MarshalByRefObject {
        private double m_MinutesToTime;
        private Timer m_Timer;

        // The client will subscribe and unsubscribe to this event
        public event TimerExpiredEventHandler TimerExpired;

        // Default: Initialize the TimerService to 4 minutes, the time required
        // to brew coffee in a French Press.
        public TimerService():this(4.0) {
        }
        
        public TimerService(double minutes) {
            Console.WriteLine("TimerService instantiated.");
            m_MinutesToTime = minutes;
            m_Timer = new Timer();
            m_Timer.Elapsed += new ElapsedEventHandler(OnElapsed);
        }
        
        public double MinutesToTime {
            get {
                return m_MinutesToTime;
            }
            set {
                m_MinutesToTime = value;
            }
        }

        public void Start() {
            if(!m_Timer.Enabled) {
                TimeSpan interval = TimeSpan.FromMinutes(m_MinutesToTime);
                m_Timer.Interval = interval.TotalMilliseconds;
                m_Timer.Enabled = true;
            }
            else {
                // TODO: Raise an exception
            }
        }
        
        private void OnElapsed(object source, ElapsedEventArgs e) {
            m_Timer.Enabled = false;

            // Fire Event
            if (TimerExpired != null) {
                // Package String in TimerServiceEventArgs
                TimerServiceEventArgs timerEventArgs = new TimerServiceEventArgs("TimerServiceEventArgs: Timer Expired.");
                Console.WriteLine("Firing TimerExpired Event");
                TimerExpired(this, timerEventArgs);
            }
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        public override Object InitializeLifetimeService() {
            ILease lease = (ILease)base.InitializeLifetimeService();
            if (lease.CurrentState == LeaseState.Initial) {
                lease.InitialLeaseTime = TimeSpan.FromMinutes(0.125);
                lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
                lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
                Console.WriteLine("TimerService: InitializeLifetimeService");
            }
             return lease;
        }
    }
}


Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2015 Microsoft