RemotingServices.GetLifetimeService(MarshalByRefObject) Method

Definition

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

C#
public static object GetLifetimeService(MarshalByRefObject obj);

Parameters

obj
MarshalByRefObject

The object to obtain lifetime service for.

Returns

The object that controls the lifetime of obj.

Exceptions

The immediate caller does not have infrastructure permission.

Examples

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

C#
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 TimerSample;

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

        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);
        }

        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:

C#
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:

C#
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.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);
            }
        }

        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;
        }
    }
}

Remarks

For the default lifetime service the returned object will be an object of type ILease. If the obj parameter is null, the method returns null.

Applies to

Toode Versioonid
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1