views:

227

answers:

2

Hi,

I am playing with the .net remoting features and there is something that I can't figure out nor find an answer in Google and is how the object disposal works.

I try to implement some kind of object pooling with remoting, for that I've list of static objects that are basicly a string and boolean state indicator.

When I request for a new remote object,(durring the consturctor) I check the pool for a free one, mark it as in-use and during the destruct of the object. the DismisObject simply marks it as "free",

  public class MyRemotableObject : MarshalByRefObject,IDisposable
{

    private AdvancedString obj;
    public MyRemotableObject()
    {
        aso = strCache.GetFreeObject();
    }
    ~MyRemotableObject()
    {
        Destroy();
    }
    public void Dispose()
    {
        Destroy();
    }
    public void SetMessage(string message)
    {
        if (obj== null) { obj= strCache.GetFreeObject(); }
        obj.str= message;
    }
    public string GetMessage()
    {
        return obj.str;          
    }
    void Destroy()
    {
        if (obj!= null)
        {
            obj.DismisObject();
            obj = null;
        }
    }
}

The timeouts work fine - after 5 minutes of now activity when I try to use the object I got remoting exception but ~MyRemotableObject() not the Dispose() functions aren't called so the object is never marked as free in the pool. Even if I close the program - still the object remains active in the pool. The only way to free it is manually call the Dispose function (which I can't do if, for example the program crashes or the user leaves is open )

Is there a way to force .net to dispose/destruct the objects when it closes the connection? (I found in some place that the CG should do that once in a while, so I opened 4 clients and crashed 2 them - the other 2 got disconnected after a while but the objcets are still marked as active)

A: 

Use objects that implement IDisposable in a using construct whenever possible.

e.g.

using (var remotableObj = new MyRemotableObject())
{
    // use it
}

More info here and here.

jpoh
Thanks but I don't think I can use "using" here, because I use the object in events (for example - when OnTextChange occurs I call SetMessage) and later on I want to use this for returning a real object (rather than just a string)I need to be able to to run some commands when the .net (forcely) closes the connection with the client or at least to be able to schedule the GC on the server side.
TheSimon
Ah. Bugger. Well Sam Saffron's suggestion sounds like it's worth a go...
jpoh
+1  A: 

You could possibly use ITrackingHandler to track when your object is disconnected and then run the Dispose code at that point.

Sam Saffron
works like a magic. Thank you alot :)
TheSimon