다음을 통해 공유


RemotingServices.GetLifetimeService(MarshalByRefObject) 메서드

정의

지정된 개체의 수명 정책을 제어하는 수명 서비스 개체를 반환합니다.

public:
 static System::Object ^ GetLifetimeService(MarshalByRefObject ^ obj);
public static object GetLifetimeService (MarshalByRefObject obj);
static member GetLifetimeService : MarshalByRefObject -> obj
Public Shared Function GetLifetimeService (obj As MarshalByRefObject) As Object

매개 변수

obj
MarshalByRefObject

수명 서비스를 가져올 개체입니다.

반환

obj의 수명을 제어하는 개체입니다.

예외

직접 실행 호출자에 인프라 권한이 없는 경우

예제

다음 코드 예제를 사용 하는 방법에 설명 합니다 GetLifetimeService 메서드를 지정된 된 개체에 대 한 수명 임대를 가져옵니다.

#using <system.dll>
#using <system.runtime.remoting.dll>
#using "timerservice.dll"

using namespace System;
using namespace System::Net::Sockets;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Http;
using namespace System::Runtime::Remoting::Messaging;
using namespace System::Runtime::Remoting::Lifetime;
using namespace TimerSample;
using namespace System::Security::Permissions;

namespace GroupCoffeeTimer
{
   public ref class TimerClient: public MarshalByRefObject, public ISponsor
   {
   public:
      [SecurityPermissionAttribute(SecurityAction::Demand, Flags=SecurityPermissionFlag::Infrastructure)]   
      TimerClient()
      {
         // Registers the HTTP Channel so that this client can receive
         // events from the remote service.
         ChannelServices::RegisterChannel( gcnew HttpChannel( 0 ), false );
         WellKnownClientTypeEntry^ remoteType = gcnew WellKnownClientTypeEntry( TimerService::typeid,"http://localhost:9000/MyService/TimerService.soap" );
         RemotingConfiguration::RegisterWellKnownClientType( remoteType );
         TimerService^ groupTimer = gcnew TimerService;
         groupTimer->MinutesToTime = 4.0;

         // Registers this client as a lease sponsor so that it can
         // prevent the expiration of the TimerService.
         ILease^ leaseObject = dynamic_cast<ILease^>(RemotingServices::GetLifetimeService( groupTimer ));
         leaseObject->Register( this );

         // Subscribes to the event so that the client can receive notifications from the server.
         groupTimer->TimerExpired += gcnew TimerExpiredEventHandler( this, &TimerClient::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^, TimerServiceEventArgs^ e )
      {
         Console::WriteLine( "TimerHelper::OnTimerExpired: {0}", e->Message );
      }
 public:
      [System::Security::Permissions::PermissionSet(System::Security::
         Permissions::SecurityAction::Demand, Name = "FullTrust")]
   virtual TimeSpan Renewal( ILease^ )
      {
         Console::WriteLine( "TimerClient: Renewal called." );
         return TimeSpan::FromMinutes( 0.5 );
      }
   };
}

int main()
{
   using namespace GroupCoffeeTimer;
   gcnew TimerClient;
}
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);
        }
    }
}
Imports System.Collections
Imports System.Net.Sockets
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Messaging
Imports System.Runtime.Remoting.Lifetime
Imports System.Security.Permissions
Imports TimerService



Public Class TimerClient
    Inherits MarshalByRefObject
    Implements ISponsor
    
    Public Shared Sub Main() 
        Dim myClient As New TimerClient()
    
    End Sub
    
    <SecurityPermission(SecurityAction.LinkDemand, Flags := SecurityPermissionFlag.Infrastructure)> _
    Public Sub New() 
        ' Registers the HTTP Channel so that this client can receive
        ' events from the remote service.
        Dim serverProv As New BinaryServerFormatterSinkProvider()
        serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full
        Dim clientProv As New BinaryClientFormatterSinkProvider()
        
        Dim props As New Hashtable()
        props("port") = 0
        Dim channel As New HttpChannel(props, clientProv, serverProv)
        ChannelServices.RegisterChannel(channel)
        
        Dim remoteType As New WellKnownClientTypeEntry(GetType(TimerService), "http://localhost:9000/MyService/TimerService.soap")
        RemotingConfiguration.RegisterWellKnownClientType(remoteType)
        
        Dim groupTimer As New TimerService()
        groupTimer.MinutesToTime = 4.0
        
        ' Registers this client as a lease sponsor so that it can
        ' prevent the expiration of the TimerService.
        Dim leaseObject As ILease = CType(RemotingServices.GetLifetimeService(groupTimer), ILease)
        leaseObject.Register(Me)
        
        ' Subscribes to the event so that the client can receive notifications from the server.
        AddHandler groupTimer.TimerExpired, AddressOf 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()
    
    End Sub
    
    
    Private Sub OnTimerExpired(ByVal [source] As Object, ByVal e As TimerServiceEventArgs) 
        Console.WriteLine("TimerHelper.OnTimerExpired: {0}", e.Message)
    
    End Sub
    
    <SecurityPermission(SecurityAction.LinkDemand, Flags := SecurityPermissionFlag.Infrastructure)> _
    Public Function Renewal(ByVal lease As ILease) As TimeSpan Implements ISponsor.Renewal
        Console.WriteLine("TimerClient: Renewal called.")
        Return TimeSpan.FromMinutes(0.5)
    
    End Function 'Renewal
End Class

를 컴파일하고이 예제를 실행 하려면 컴파일 및 서버, timerserver.exe, 및는 공유 라이브러리를 컴파일 timerservice.dll 실행 해야 합니다.

Timerserver.exe 소스는 다음과 같습니다.

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();
        }
    }
}
Imports System.Collections
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
Imports System.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Lifetime
Imports System.Timers



Public Class TimerServer
    
    Public Shared Sub Main() 
        
        Dim serverProv As New BinaryServerFormatterSinkProvider()
        serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full
        Dim clientProv As New BinaryClientFormatterSinkProvider()
        
        Dim props As New Hashtable()
        props("port") = 9000
        Dim channel As New HttpChannel(props, clientProv, serverProv)
        ChannelServices.RegisterChannel(channel)
        RemotingConfiguration.RegisterWellKnownServiceType(GetType(TimerService), "MyService/TimerService.soap", WellKnownObjectMode.Singleton)
        
        Console.WriteLine("Press enter to end the server process.")
        Console.ReadLine()
    
    End Sub
End Class

Timerservice.dll 소스는 다음과 같습니다.

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;
        }
    }
}
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
Imports System.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Lifetime
Imports System.Security.Permissions
Imports System.Timers


' Define the event arguments
<Serializable()>  _
Public Class TimerServiceEventArgs
    Inherits EventArgs
    Private m_Message As String
    
    Public Sub New(ByVal message As String) 
        m_Message = message
    
    End Sub
    
    
    Public ReadOnly Property Message() As String 
        Get
            Return m_Message
        End Get
    End Property
End Class


' Define the delegate for the event
Public Delegate Sub TimerExpiredEventHandler(ByVal sender As Object, ByVal e As TimerServiceEventArgs) 

' Define the remote service class

Public Class TimerService
    Inherits MarshalByRefObject
    Private m_MinutesToTime As Double
    Private m_Timer As Timer
    
    ' The client will subscribe and unsubscribe to this event
    Public Event TimerExpired As TimerExpiredEventHandler
    
    
    ' Default: Initialize the TimerService to 4 minutes, the time required
    ' to brew coffee in a French Press.
    Public Sub New() 
        MyClass.New(4.0)
    
    End Sub
    
    
    Public Sub New(ByVal minutes As Double) 
        Console.WriteLine("TimerService instantiated.")
        m_MinutesToTime = minutes
        m_Timer = New Timer()
        AddHandler m_Timer.Elapsed, AddressOf OnElapsed
    
    End Sub
    
    
    Public Property MinutesToTime() As Double 
        Get
            Return m_MinutesToTime
        End Get
        Set
            m_MinutesToTime = value
        End Set
    End Property
    
    
    Public Sub Start() 
        If Not m_Timer.Enabled Then
            Dim interval As TimeSpan = TimeSpan.FromMinutes(m_MinutesToTime)
            m_Timer.Interval = interval.TotalMilliseconds
            m_Timer.Enabled = True
        Else
        End If
     ' TODO: Raise an exception
    End Sub
    
    
    Private Sub OnElapsed(ByVal [source] As Object, ByVal e As ElapsedEventArgs) 
        m_Timer.Enabled = False
        
        ' Fire Event
        If Not (TimerExpiredEvent Is Nothing) Then
            ' Package String in TimerServiceEventArgs
            Dim timerEventArgs As New TimerServiceEventArgs("TimerServiceEventArgs: Timer Expired.")
            Console.WriteLine("Firing TimerExpired Event")
            RaiseEvent TimerExpired(Me, timerEventArgs)
        End If
    
    End Sub
    
    <SecurityPermission(SecurityAction.LinkDemand, Flags := SecurityPermissionFlag.Infrastructure)> _
    Public Overrides Function InitializeLifetimeService() As [Object] 
        Dim lease As ILease = CType(MyBase.InitializeLifetimeService(), ILease)
        If lease.CurrentState = LeaseState.Initial Then
            lease.InitialLeaseTime = TimeSpan.FromMinutes(0.125)
            lease.SponsorshipTimeout = TimeSpan.FromMinutes(2)
            lease.RenewOnCallTime = TimeSpan.FromSeconds(2)
            Console.WriteLine("TimerService: InitializeLifetimeService")
        End If
        Return lease
    
    End Function 'InitializeLifetimeService
End Class

설명

기본 수명 서비스에 대 한 반환된 된 개체 형식의 개체 수는 ILease합니다. 경우는 obj 매개 변수가 null, 메서드가 반환 null합니다.

적용 대상