我应该处置局部类变量吗? - c#

我有一个遗留应用程序,在该应用程序中我会不时收到OutOfMemory异常。我正在尝试调试和解决问题。我正在考虑的一种选择是使用Dispose()方法。我知道任何实现IDisposable接口的对象都可以让我在其上调用Dispose()方法,但是它也有助于释放资源以将类级别变量设置为null吗?例如ArrayListHashtable

我确实在互联网上搜索并找到了一些帖子,但对于是否要null对象还是有些困惑。

我正在尝试的代码

public class RepET : base_entitlement, IDisposable
{
    #region Public Member Variables
    public const int ENTITLEMENT_TYPE = 7;
    public string table = "acc_rep";
    public ArrayList country_list;
    public Hashtable data;
    public ArrayList survey_dates;
    public ArrayList city_list;
    public Dictionary<string, Dictionary<string, string>> cityData;
    public Dictionary<string, Dictionary<string, string>> reportCity_list;
    public RepET(string entId)
    {
        if (id != "0")
        {
            id = entId;
            // if we cant load the metadata then load the full records & build the metadata

            if (!LoadFromMetaDb(id, ENTITLEMENT_TYPE))
            {
                if (this.load_entitlements())
                {
                    serialize_to_metadb(this, ENTITLEMENT_TYPE);
                }
            }
        }
    }
    #endregion

    public bool load_entitlements()
    {
        //  loads this entitlement from the metadata
        this.data = new Hashtable();
        this.survey_dates = new ArrayList();
        this.city_list = new ArrayList();
        //SqlQueries.ProcessingStarted(id);
        var sdates = SqlQueries.GetNewestSurveyByET(this.table, id, "acc_rep");

        if (sdates.Count == 0) return false;
        else
        {
            //delete ent 4 if already exist as its regenerated here
            check_EntFile_Created(id, Constants.ENTITLEMENT_TYPE_RP.ToString(), true);
            o_report_entitlements = new report_entitlements(id);

            reportCity_list = new Dictionary<string, Dictionary<string, string>>();
            foreach (string sd in sdates)
            {
                ent_by_survey_date(sd.Trim(), true);
                this.survey_dates.Add(sd.Trim());
            }
            o_report_entitlements.serialize_to_metadb(o_report_entitlements, Constants.ENTITLEMENT_TYPE_RP);

            return true;
        }
    }

    public bool ent_by_survey_date(string survey_date, bool modify_report_entitlements = false)
    {

        //if (modify_report_entitlements) {
        //    ArrayList countryArray;
        //}

        var dt = SqlQueries.Ent_by_survey_date(table, id, survey_date, "acc");
        if (dt.Rows.Count == 0)
        {
            return false;
        }
        else
        {
            country_list = new ArrayList();
            city_list = new ArrayList();

            Dictionary<string, ArrayList> countryCodes = new Dictionary<string, ArrayList>();

            foreach (DataRow row in dt.Rows)
            {
                string current_city_code = row["city_code"].ToString().Trim();
                string current_report_type = row["report_type"].ToString().Trim();

                if (!string.IsNullOrEmpty(current_city_code))
                {
                    Dictionary<string, string> currentCityReportList = new Dictionary<string, string>();
                    if (!reportCity_list.ContainsKey(survey_date))
                    {
                        reportCity_list[survey_date] = new Dictionary<string, string>();
                        reportCity_list[survey_date].Add(current_city_code, current_report_type);
                    }
                    else if (reportCity_list != null && reportCity_list.ContainsKey(survey_date) && !reportCity_list[survey_date].ContainsKey(current_city_code))
                    {
                        reportCity_list[survey_date].Add(current_city_code, current_report_type);
                    }

                    if (modify_report_entitlements)
                    {

                        string current_country_code = get_country_code_by_city(current_city_code);

                        if (!country_list.Contains(current_country_code))
                        {
                            country_list.Add(current_country_code);
                            foreach (var item in ((System.Reflection.TypeInfo)(o_report_entitlements.GetType())).DeclaredFields)
                            {
                                if (item.Name == "data")
                                {
                                    Hashtable tempObj = (Hashtable)item.GetValue(o_report_entitlements);
                                    if (tempObj != null)
                                    {
                                        countryCodes = (Dictionary<string, ArrayList>)tempObj[id];
                                        if (countryCodes != null && !countryCodes.ContainsKey(current_country_code))
                                            this.o_report_entitlements.add_to_array(current_country_code, "ACC", "", ref countryCodes);
                                        else if (countryCodes != null && countryCodes.ContainsKey(current_country_code) && !countryCodes[current_country_code].Contains("ACC"))
                                            this.o_report_entitlements.add_to_array(current_country_code, "ACC", "", ref countryCodes);
                                        else if (!countryCodes.ContainsKey(current_country_code))
                                            this.o_report_entitlements.add_to_array(current_country_code, "ACC", "", ref countryCodes);
                                    }
                                    else
                                    {
                                        if (countryCodes == null)
                                            countryCodes = new Dictionary<string, ArrayList>();
                                        this.o_report_entitlements.add_to_array(current_country_code, "ACC", "", ref countryCodes);
                                    }
                                }
                            }
                        }
                    }

                    if (!city_list.Contains(current_city_code))
                    {
                        city_list.Add(current_city_code);
                    }
                    if (!currentCityReportList.ContainsKey(current_city_code))
                    {
                        currentCityReportList.Add(current_city_code, current_report_type);
                    }
                    if (!data.ContainsKey(survey_date))
                    {
                        data[survey_date] = new Hashtable();
                    }
                    switch ((((Hashtable)this.data[survey_date])).GetType() == typeof(Dictionary<string, string>))
                    {
                        case true:
                            break;
                        case false:
                        default:
                            ((Hashtable)this.data[survey_date])[current_city_code] = new Dictionary<string, string>();
                            (((Dictionary<string, string>)((Hashtable)this.data[survey_date])[current_city_code])["city_code"]) = current_city_code;
                            //(((Dictionary<string, string>)((Hashtable)this.data[survey_date])[current_city_code])["city_code"])


                            //(((Dictionary<string, ArrayList>)((Hashtable)this.data[survey_date])[current_city_code])["report_type"]) = new ArrayList();
                            (((Dictionary<string, string>)((Hashtable)this.data[survey_date])[current_city_code])["report_type"]) = current_report_type;
                            //((Dictionary<string, string>)((Hashtable)this.data[survey_date])[current_city_code])["report_type"] = current_report_type;
                            break;
                    }
                }
            }
        }
        return true;
    }

    public string get_country_code_by_city(string city_code)
    {

        load_city_list();
        string returnItem = null;
        foreach (var item in cityData)
        {
            Dictionary<string, string> subItem = item.Value;
            if (subItem.ContainsKey(city_code))
            {
                returnItem += item.Key;
            }
        }
        return returnItem;
    }

    public bool load_city_list()
    {
        if (GlobalObjs.dtCityList.Rows.Count == 0)
            GlobalObjs.dtCityList = SqlQueries.LoadCityList();

        //var dt = SqlQueries.LoadCityList();
        if (GlobalObjs.dtCityList.Rows.Count == 0)
        {
            return false;
        }
        Dictionary<string, string> cityList = new Dictionary<string, string>();
        cityData = new Dictionary<string, Dictionary<string, string>>();
        foreach (DataRow row in GlobalObjs.dtCityList.Rows)
        {
            string Country_Code = row["Country_Code"].ToString().Trim();
            string City_Code = row["City_Code"].ToString().Trim();
            string City_Name = row["Name"].ToString().Trim();

            if (!cityData.ContainsKey(Country_Code))
            {
                cityData.Add(Country_Code, new Dictionary<string, string>());
            }

            Dictionary<string, string> tempList = cityData[Country_Code];
            if (!tempList.ContainsKey(City_Code))
            {
                tempList.Add(City_Code, City_Name);
                //cityList.Add(City_Code, City_Name);
                cityData[Country_Code] = tempList;
            }

        }
        return true;
    }



    // Flag: Has Dispose already been called?
    bool disposed = false;

    // Protected implementation of Dispose pattern.
    protected void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            country_list = null;
            data = null;
            survey_dates = null;
            city_list = null;
            cityData = null;
            reportCity_list = null;
        }

        disposed = true;
    }
    public void Dispose()
    {
        Dispose(true);
    }
}

这对内存异常有帮助吗?

参考方案

将字段设置为null的唯一时间将对垃圾回收有所不同是,如果您仍然以某种方式使RepET实例可访问,在这种情况下,真正的解决方案是:确保RepET实例不再可达!将字段设置为null可以解决实际问题。

最好使用Dispose()级联connectioncmd之类的东西,但是...我的另一部分认为更好的方法是不存储它们,即按需获取连接并保持cmd完全位于使用它的地方;就像是:

using (var conn = SomeHelper.CreateConnection())
{
    // your "cmd" code in here, via "using" - or
    // perhaps via "Dapper" and let it worry about that
}

但是,真正的技巧是,如果这是真正的问题,那就是找到持有该实例的东西。没有上下文很难评论,但是:事件和静态缓存是开始寻找的好地方。

如何从php中获取datatables jQuery插件的json数据 - php

我是PHP的新手,正在尝试使用Datatables jQuery插件。我知道我必须从.php文件中获取数据,然后在数据表中使用它,但是我似乎无法通过ajax将其传递给数据表。我设法从数据库中获取数据,并对其进行json编码,但是后来我不知道如何在我的index.php文件中调用它,并在其中显示它。我究竟做错了什么?这是我的代码:HTML(已编辑): <…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

改造正在返回一个空的响应主体 - java

我正在尝试使用Retrofit和Gson解析一些JSON。但是,我得到的响应机构是空的。当我尝试从对象中打印信息时,出现NullPointerException。我确保URL正确,并且我也确保POJO也正确。我正在使用jsonschema2pojo来帮助创建POJO类。这是我要解析的JSON{ "?xml": { "@versi…

Java中的Boolean.valueOf(String)和BooleanUtils.toBoolean(String)? - java

我在Boolean.valueOf(String)和BooleanUtils.toBoolean(String)之间有一个不同的问题 。我使用我的应用程序就像代码BooleanUtils.toBoolean(defaultInfoRow.getFolderType())一样,而Boolean.valueOf(defaultInfoRow.getFolderT…

jQuery发布不会将数据发布到ASP.NET API控制器 - javascript

我有一次噩梦般的时间通过jquery post将数据发送到ASP.NET Controller。这是JSON.stringify之后的数据:[{"scheduleTaskID":"203","task":"Permit","baselineDate":…