Remoting 采取了一种称之为 "租约" 的机制来管理远程对象(Singleton、CAO)的生存期策略。每个应用程序域中都有一个租约管理器(LifetimeServices),它负责管理所有参与生存期的远程对象租约。租约管理器定期检查所有租约以确定过期的租约时间,如果租约已过期,将向该对象发起人(Sponsor)的发送请求,查询是否有谁要续订租约,若没有任何发起人续订该租约,租约将被移除,该远程对象也会被删除等待垃圾回收器回收。如果远程对象被发起人多次续订租约或被客户端持续调用,其生存期可以比其生存期租约长得多。 所谓发起人 (Sponsor,MSDN 翻译为"主办方",真别扭!) 就是一个或多个与远程对象关联,用于定义租约延长时间的对象。租约管理器通过回调发起人方法(ISponsor.Renewal)来查询是否续订租约。发起人需要继承自 MarshalByRefObject,且必须实现 ISponsor 接口。在 System.Runtime.Remoting.Lifetime 名字空间中,Framework 为我们提供了一个缺省实现 —— ClientSponsor。 租约参数 当参与生存期管理的远程对象被创建后,其租约被设置为 LifetimeServices.LeaseTime 或 ILease.InitialLeaseTime。 我们可以通过 ILease.CurrentLeaseTime 来检查对象租约过期的剩余时间。 客户端调用远程对象方法时,会发生隐式续订租约行为。当 CurrentLeaseTime 小于 RenewOnCallTime,则租约被设置为 RenewOnCallTime。 租约管理器每隔一定时间(LeaseManagerPollTime)检查一次租约列表,如果某租约过期则通知其发起人,询问是否进行续订。如发起人未能在 SponsorshipTimeout 时间内响应,则移除该主办方并调用另一主办方。如果没有其他主办方,则租约过期,且垃圾回收器将处置该远程对象。 租约过期试验 using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.CompilerServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Lifetime; namespace Learn.Library.Remoting