4

I've wrote a piece of code similar to the example in this post: .NET Remoting callback (Pass a callback object to a remote method).

As I found out, if I didn't override MarshalByRefObject.InitializeLifetimeService() After a while, the server failed calling the callback. So I overriden it to return null (infinite lifetime) and it works.

But now I'm a bit worried about garbage collecton:

  1. Will such an object be collected by GC as usual, or remain alive because it was remoted?
  2. I found this method: RemotingServices.Disconnect()

If I call it on my callback object, will it guarantee that the lifetime policy will become irrelevant and it will be garbage collected?

I wanted an expert opinion if I'm doing it right.

Thanks, Gil.

PS. I'm working under the constraints of .NET 2.0, so recommendations to switch to WCF, while correct, are irrelevant. :)

Community
  • 1
  • 1
Jimbidf
  • 391
  • 1
  • 15
  • 1
    .NET remoting is much more powerful than WCF. I still dont know why it is sold as a replacement. – leppie Jun 17 '12 at 14:52

2 Answers2

4

Ok, it seems that the approach proved itself.

I used an unlimited lease by returning null in MarshalByRefObject.InitializeLifetimeService().
Then, calling RemotingServices.Disconnect() allowed the object to be released properly.

Jimbidf
  • 391
  • 1
  • 15
1

If you override InitializeLifetimeService and return null, your object will never be garbage collected.

If you don't want your instance to live forever, then you need to go into Sponsors and Leases - basically you get a callback when .NET is about to expire the lease and GC the object, giving you a chance to renew the lease.

See http://msdn.microsoft.com/en-us/magazine/cc300474.aspx for a good overview of sponsorship and leases.

rupertb
  • 89
  • 3
  • Is that true even if I use RemotingServices.Disconnect()? – Jimbidf Oct 11 '12 at 17:58
  • The magazine link no longer works - according to https://stackoverflow.com/a/25315226/155892 it was in the *December 2003* issue though which can be downloaded in CHM format from the same page. – Mark Sowul Sep 09 '18 at 20:26