简体   繁体   中英

remoting and destructors in c#

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)

您可以使用ITrackingHandler跟踪对象断开连接的时间,然后在该点运行Dispose代码。

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

eg

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

More info here and here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM