Search code examples
c#.net-remoting

How to dispose resources in client-side activated object once it's released?


A remotable class is used by client-side activation. This class uses some local resources which should be disposed as soon as the object is released. How to ensure the resources will be disposed? Ideally need to catch no sponsor renew event.


Solution

  • A variant with timer:

        class RemotableObject {
    
            System.Timer _tmr;
            System.Runtime.Remoting.Lifetime.ILease _lts;
    
            public RemotableObject() {
                _lts = (ILease)GetLifetimeService();
                _tmr = new Timer(OnFire, null, 10000, 10000);
            }
    
            void OnFire(object state) {
                if (_lts.CurrentState == LeaseState.Expired) { _tmr.Dispose(); Dispose(); }
            }
    
            void Dispose() {
                // ...
            }
        }