RemotingServices.GetLifetimeService(MarshalByRefObject) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定したオブジェクトの有効期間ポリシーを制御する、有効期間サービス オブジェクトを返します。
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
の有効期間を制御するオブジェクト。
例外
直前の呼び出し元に、インフラストラクチャ アクセス許可がありません。
例
次のコード例では、 メソッドを使用 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
この例をコンパイルして実行するには、timerservice.dll、サーバーのコンパイルと実行、timerserver.exe、および共有ライブラリのコンパイルを行う必要があります。
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
。
適用対象
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET