Share via


ILease 接口

定义远程处理生存期服务所使用的生存期租约对象。

**命名空间:**System.Runtime.Remoting.Lifetime
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
<ComVisibleAttribute(True)> _
Public Interface ILease
用法
Dim instance As ILease
[ComVisibleAttribute(true)] 
public interface ILease
[ComVisibleAttribute(true)] 
public interface class ILease
/** @attribute ComVisibleAttribute(true) */ 
public interface ILease
ComVisibleAttribute(true) 
public interface ILease

备注

分布式垃圾回收控制何时可以删除服务器应用程序。传统上,分布式垃圾回收使用引用计数和 Ping 进行控制。这在每个对象有少数几个客户端时可以很好地工作,但在每个对象有数千个客户端时效率很低。生存期服务可采用传统分布式垃圾回收器的功能,并在客户端数目增加时能很好地扩展。

生存期服务将租约与每个远程激活的对象关联。当租约过期时,对象将被移除。租约可以指定某对象具有无限长的生存期。

每个 AppDomain 都包含一个管理域中租约的租约管理器。租约管理器定期检查租约是否到期。如果租约已经到期,则可以通过移除其对该租约的引用来取消它,或通过调用该租约的一个或多个主办方来续订它。

租约包含确定其策略的属性以及续订租约时间的方法。租约公开 ILease 接口。

示例

下面的示例由三个程序集组成:一个客户端,一个服务器以及一个由客户端和服务器共享的库。首先编译库,然后是客户端和服务器。下面的命令编译 Visual Basic 文件;要编译 C# 文件,应使用 csc 命令和 .cs 文件扩展名。显示的文件名只是建议性的。

 vbc /t:library ILeaseShare.vb
 vbc /r:ILeaseShare.dll ILeaseServer.vb
 vbc /r:ILeaseShare.dll /r:System.Runtime.Remoting.dll ILeaseClient.vb

没有必要全部使用 Visual Basic 文件或全部使用 C# 文件;一旦完成编译,这些程序集就能一起工作,而不论源代码的语言是什么。若要运行示例,请打开两个命令窗口。首先运行服务器,然后运行客户端。如果将客户端和服务器分别放在不同的文件夹下,就必须在每个文件夹下放置一个共享库的副本。

下面的代码用于共享库。

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Lifetime
Imports System.Security.Permissions

Namespace RemotingSamples
   Public Class HelloService
      Inherits MarshalByRefObject

      Public Function HelloMethod(name As String) As String
         Console.WriteLine("Hello " + name)
         Return "Hello " + name
      End Function 'HelloMethod

<SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.Infrastructure)> _
      Public Overrides Function InitializeLifetimeService() As Object
         Dim baseLease As ILease = CType(MyBase.InitializeLifetimeService(), ILease)
         If baseLease.CurrentState = LeaseState.Initial Then
            ' For demonstration the initial time is kept small.
            ' in actual scenarios it will be large.
            baseLease.InitialLeaseTime = TimeSpan.FromSeconds(15)
            baseLease.RenewOnCallTime = TimeSpan.FromSeconds(15)
            baseLease.SponsorshipTimeout = TimeSpan.FromMinutes(2)
         End If
         Return baseLease
      End Function 'InitializeLifetimeService
   End Class 'HelloService
End Namespace 'RemotingSamples
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;

namespace RemotingSamples
{
   public class HelloService : MarshalByRefObject
   {
      public string HelloMethod(string name)
      {
         Console.WriteLine("Hello " + name);
         return "Hello " + name;
      }

[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)]
      public override object InitializeLifetimeService()
      {
         ILease baseLease = (ILease)base.InitializeLifetimeService();
         if (baseLease.CurrentState == LeaseState.Initial)
         {
            // For demonstration the initial time is kept small.
            // in actual scenarios it will be large.
            baseLease.InitialLeaseTime = TimeSpan.FromSeconds(15);
            baseLease.RenewOnCallTime = TimeSpan.FromSeconds(15);
            baseLease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
         }
         return baseLease;
      }
   }
}
#using <system.dll>
#using <system.runtime.remoting.dll>

using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Lifetime;

namespace RemotingSamples
{
   public ref class HelloService: public MarshalByRefObject
   {
   public:
      String^ HelloMethod( String^ name )
      {
         Console::WriteLine( "Hello {0}", name );
         return "Hello {0}",name;
      }

      [System::Security::Permissions::SecurityPermissionAttribute
      (System::Security::Permissions::SecurityAction::LinkDemand, 
      Flags=System::Security::Permissions::SecurityPermissionFlag::Infrastructure)]
      virtual Object^ InitializeLifetimeService() override
      {
         ILease^ baseLease = dynamic_cast<ILease^>(MarshalByRefObject::InitializeLifetimeService());
         if ( baseLease->CurrentState == LeaseState::Initial )
         {
            
            // For demonstration the initial time is kept small.
            // in actual scenarios it will be large.
            baseLease->InitialLeaseTime = TimeSpan::FromSeconds( 15 );
            baseLease->RenewOnCallTime = TimeSpan::FromSeconds( 15 );
            baseLease->SponsorshipTimeout = TimeSpan::FromMinutes( 2 );
         }

         return baseLease;
      }

   };

}

下面的代码用于客户端程序集。

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
Imports System.Runtime.Remoting.Lifetime

Namespace RemotingSamples


   Class HelloClient

      Shared Sub Main()
         ' Register the channel.
         Dim myChannel As New TcpChannel()
         ChannelServices.RegisterChannel(myChannel)
         RemotingConfiguration.RegisterActivatedClientType( _
                           GetType(HelloService), "Tcp://localhost:8085")

         Dim myTimeSpan As TimeSpan = TimeSpan.FromMinutes(10)

         ' Create a remote object.
         Dim myService As New HelloService()

         Dim myLease As ILease
         myLease = CType(RemotingServices.GetLifetimeService(myService), ILease)
         If myLease Is Nothing Then
            Console.WriteLine("Cannot lease.")
            Return
         End If

         Console.WriteLine("Initial lease time is " & myLease.InitialLeaseTime.ToString())
         Console.WriteLine("Current lease time is " & myLease.CurrentLeaseTime.ToString())
         Console.WriteLine("Renew on call time is " & myLease.RenewOnCallTime.ToString())
         Console.WriteLine("Sponsorship timeout is " & myLease.SponsorshipTimeout.ToString())
         Console.WriteLine("Current lease state is " & myLease.CurrentState.ToString())
         ' Register with a sponser.
         Dim mySponsor As New ClientSponsor()
         myLease.Register(mySponsor)
         Console.WriteLine("Wait for lease to expire (approx. 15 seconds)...")
         System.Threading.Thread.Sleep(myLease.CurrentLeaseTime)
         Console.WriteLine("Current lease time before renewal is " & _
                        myLease.CurrentLeaseTime.ToString())

         ' Renew the lease time.
         myLease.Renew(myTimeSpan)
         Console.WriteLine("Current lease time after renewal is " + _
                        myLease.CurrentLeaseTime.ToString())

         ' Call the Remote method.
         Console.WriteLine("Remote method output is " + myService.HelloMethod("Microsoft"))

         myLease.Unregister(mySponsor)
         GC.Collect()
         GC.WaitForPendingFinalizers()

         ' Register with lease time of 15 minutes.
         myLease.Register(mySponsor, TimeSpan.FromMinutes(15))
         Console.WriteLine("Registered client with lease time of 15 minutes.")
         Console.WriteLine("Current lease time is " + myLease.CurrentLeaseTime.ToString())

         ' Call the Remote method.
         Console.WriteLine("Remote method output is " + myService.HelloMethod("Microsoft"))
         myLease.Unregister(mySponsor)
      End Sub 'Main
   End Class 'HelloClient

End Namespace 'RemotingSamples
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Lifetime;

namespace RemotingSamples
{
   class HelloClient
   {
      static void Main()
      {
         // Register the channel.
         TcpChannel myChannel = new TcpChannel ();
         ChannelServices.RegisterChannel(myChannel);
         RemotingConfiguration.RegisterActivatedClientType(
                                typeof(HelloService),"Tcp://localhost:8085");

         TimeSpan myTimeSpan = TimeSpan.FromMinutes(10);

         // Create a remote object.
         HelloService myService = new HelloService();

         ILease myLease;
         myLease = (ILease)RemotingServices.GetLifetimeService(myService);
         if (myLease == null)
         {
            Console.WriteLine("Cannot lease.");
            return;
         }

         Console.WriteLine ("Initial lease time is " + myLease.InitialLeaseTime);
         Console.WriteLine ("Current lease time is " + myLease.CurrentLeaseTime);
         Console.WriteLine ("Renew on call time is " + myLease.RenewOnCallTime);
         Console.WriteLine ("Sponsorship timeout is " + myLease.SponsorshipTimeout);
         Console.WriteLine ("Current lease state is " + myLease.CurrentState.ToString());
         // Register with a sponser.
         ClientSponsor mySponsor = new ClientSponsor();
         myLease.Register(mySponsor);
         Console.WriteLine("Wait for lease to expire (approx. 15 seconds)...");
         System.Threading.Thread.Sleep(myLease.CurrentLeaseTime);
         Console.WriteLine ("Current lease time before renewal is " + myLease.CurrentLeaseTime);

         // Renew the lease time.
         myLease.Renew(myTimeSpan);
         Console.WriteLine ("Current lease time after renewal is " + myLease.CurrentLeaseTime);

         // Call the Remote method.
         Console.WriteLine("Remote method output is " + myService.HelloMethod("Microsoft"));

         myLease.Unregister(mySponsor);
         GC.Collect();
         GC.WaitForPendingFinalizers();

         // Register with lease time of 15 minutes.
         myLease.Register(mySponsor,TimeSpan.FromMinutes(15));
         Console.WriteLine("Registered client with lease time of 15 minutes.");
         Console.WriteLine ("Current lease time is " + myLease.CurrentLeaseTime);

         // Call the Remote method.
         Console.WriteLine("Remote method output is " + myService.HelloMethod("Microsoft"));
         myLease.Unregister(mySponsor);
      }
   }
}
#using <system.dll>
#using <system.runtime.remoting.dll>
#using <ILease_Share.dll>

using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Tcp;
using namespace System::Runtime::Remoting::Lifetime;
using namespace RemotingSamples;

int main()
{
   // Register the channel.
   TcpChannel^ myChannel = gcnew TcpChannel;
   ChannelServices::RegisterChannel( myChannel );
   RemotingConfiguration::RegisterActivatedClientType( HelloService::typeid, "Tcp://localhost:8085" );
   TimeSpan myTimeSpan = TimeSpan::FromMinutes( 10 );

   // Create a remote object.
   HelloService ^ myService = gcnew HelloService;
   ILease^ myLease;
   myLease = dynamic_cast<ILease^>(RemotingServices::GetLifetimeService( myService ));
   if ( myLease == nullptr )
   {
      Console::WriteLine( "Cannot lease." );
      return  -1;
   }

   Console::WriteLine( "Initial lease time is {0}", myLease->InitialLeaseTime );
   Console::WriteLine( "Current lease time is {0}", myLease->CurrentLeaseTime );
   Console::WriteLine( "Renew on call time is {0}", myLease->RenewOnCallTime );
   Console::WriteLine( "Sponsorship timeout is {0}", myLease->SponsorshipTimeout );
   Console::WriteLine( "Current lease state is {0}", myLease->CurrentState );

   // Register with a sponser.
   ClientSponsor^ mySponsor = gcnew ClientSponsor;
   myLease->Register( mySponsor );
   Console::WriteLine( "Wait for lease to expire (approx. 15 seconds)..." );
   System::Threading::Thread::Sleep( myLease->CurrentLeaseTime );
   Console::WriteLine( "Current lease time before renewal is {0}", myLease->CurrentLeaseTime );

   // Renew the lease time.
   myLease->Renew( myTimeSpan );
   Console::WriteLine( "Current lease time after renewal is {0}", myLease->CurrentLeaseTime );

   // Call the Remote method.
   Console::WriteLine( "Remote method output is {0}", myService->HelloMethod( "Microsoft" ) );
   myLease->Unregister( mySponsor );
   GC::Collect();
   GC::WaitForPendingFinalizers();

   // Register with lease time of 15 minutes.
   myLease->Register( mySponsor, TimeSpan::FromMinutes( 15 ) );
   Console::WriteLine( "Registered client with lease time of 15 minutes." );
   Console::WriteLine( "Current lease time is {0}", myLease->CurrentLeaseTime );

   // Call the Remote method.
   Console::WriteLine( "Remote method output is {0}", myService->HelloMethod( "Microsoft" ) );
   myLease->Unregister( mySponsor );
}

下面的代码用于服务器程序集。

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
Imports System.Runtime.Remoting.Lifetime

Namespace RemotingSamples
   Class HelloServer

      Shared Sub Main()
         Dim myChannel As New TcpChannel(8085)
         ChannelServices.RegisterChannel(myChannel)
         RemotingConfiguration.RegisterActivatedServiceType(GetType(HelloService))
         Console.WriteLine("Server started.")
         Console.WriteLine("Hit enter to terminate...")
         Console.Read()
      End Sub 'Main
   End Class 'HelloServer
End Namespace 'RemotingSamples
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Lifetime;


namespace RemotingSamples
{
   class HelloServer
   {
      static void Main()
      {
         TcpChannel myChannel = new TcpChannel (8085);
         ChannelServices.RegisterChannel(myChannel);
         RemotingConfiguration.RegisterActivatedServiceType(typeof(HelloService));
         Console.WriteLine("Server started.");
         Console.WriteLine("Hit enter to terminate...");
         Console.Read();
      }
   }
}
#using <system.dll>
#using <system.runtime.remoting.dll>
#using <ILease_Share.dll>

using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Tcp;
using namespace System::Runtime::Remoting::Lifetime;
using namespace RemotingSamples;

int main()
{
   TcpChannel^ myChannel = gcnew TcpChannel( 8085 );
   ChannelServices::RegisterChannel( myChannel );
   RemotingConfiguration::RegisterActivatedServiceType( HelloService::typeid );
   Console::WriteLine( "Server started." );
   Console::WriteLine( "Hit enter to terminate..." );
   Console::Read();
}

平台

Windows 98、Windows 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

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

ILease 成员
System.Runtime.Remoting.Lifetime 命名空间