OutOfMemoryException在我的应用程序中,我尝试使用using和dispose()



我刚刚读了关于同一个问题的所有答案,但它们没有帮助。

这是我的c#代码中太长的一部分。它有很多SQLConnection和2个定时器。

Indirizzo nuovoInd = new Indirizzo();
SqlConnection cn = new SqlConnection(nuovoInd.OttieniIP());
string strSql = "INSERT INTO Pietanze(nome,prezzo,ingredienti,cod_cat) VALUES ('"+nome+"','"+prezzo+"','"+ingredienti+"','"+contCat+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();

public static float GetCoperti(int codOrdine)
    {
        float copertiTot = 0;
        List<Ordine> ordini = new List<Ordine>();
        VisualizzaOrdini.Form1.Indirizzo nuovoInd = new VisualizzaOrdini.Form1.Indirizzo();
        SqlConnection cn = new SqlConnection(nuovoInd.OttieniIP());
        string strSql = "SELECT codo,tavolo,InsertDate,nCoperti,costoCoperti FROM Ordini, Riga_Ordine, Coperti where codo=cod_or and cod_or = '"+ codOrdine + "' ORDER BY InsertDate DESC";
        SqlCommand cmd = new SqlCommand(strSql, cn);
        cn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            Ordine currO = new Ordine();
            currO.Data = Convert.ToDateTime(dr["InsertDate"]);
            currO.Coperti = (int)dr["nCoperti"];
            currO.PrezzoCoperto = Convert.ToSingle(dr["costoCoperti"]);
            currO.Tavolo = dr["tavolo"].ToString();
            currO.Codice = (int)dr["codo"];
            copertiTot = (currO.PrezzoCoperto * Convert.ToSingle(currO.Coperti));
            ordini.Add(currO);
        }
        return copertiTot;
    }

我正在为代码抛出OutOfMemoryException这一事实而挣扎。是什么原因造成的?我该如何解决?

可能是在获取记录后没有关闭SqlDataReader对象的问题,您必须显式关闭它。

dr.Close();

此外,在关闭读卡器后关闭连接,或者按照Habib的建议使用using块。

cn.Close();

首先,打开数据库连接以完全执行代码是不好的做法。将execute语句分配给某个DataTable。它将为您提供数据库的本地副本。它处理起来也更方便,而且肯定不会出现内存不足的异常。

数据表DTab=cmdexecuteReader();数据集DSet=cmdexecuteReader()

两者都会给你带来预期的结果。

最新更新