简体   繁体   English

C#中的远程处理程序和析构函数

[英]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. 我正在使用.net远程功能,有些东西我无法弄清楚,也无法在Google中找到答案,这是对象处理的工作方式。

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", DismisObject只是将其标记为“免费”,

  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. 超时可以正常工作-当我尝试使用该对象时,经过5分钟的活动后,我得到了远程处理异常,但是未调用〜MyRemotableObject()而不是Dispose()函数,因此该对象在池中从未标记为空闲。 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 ) 释放它的唯一方法是手动调用Dispose函数(例如,程序崩溃或用户离开时,我就无法打开它)

Is there a way to force .net to dispose/destruct the objects when it closes the connection? 有没有办法在关闭连接时强制.net处理/销毁对象? (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) (我发现某个地方的CG应该偶尔执行一次,所以我打开了4个客户端,使2个客户端崩溃了-一段时间后其他2个客户端断开了连接,但objcets仍然标记为活动状态)

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

Use objects that implement IDisposable in a using construct whenever possible. 尽可能usingusing构造中实现IDisposable的对象。

eg 例如

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

More info here and here . 更多信息在这里这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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