c# - 在 C# .NET 中清理 ODBC DSN

标签 c# memory-management memory-leaks odbc paradox

我正在使用 C# 和 OBDC DSN 连接到 Paradox 数据库。如果我打开和关闭每个连接,我似乎会泄漏内存。

我的代码基本上是:

            csb.Dsn = "DNSName";
            OdbcConnection con = new OdbcConnection(csb.ConnectionString);
            con.Open();

            OdbcCommand comm= new OdbcCommand("SELECT * FROM Tabl", con);
            OdbcDataReader reader= null;
            try
            {
                reader= comm.ExecuteReader();
                for (int count = 0; (count < 5 && reader.Read()); ++count)
                {
                    //Read
                }
            }
            finally
            {
                if (reader!= null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (comm!= null)
                {
                    con.Close();
                    con.Dispose();
                    OdbcConnection.ReleaseObjectPool();
                    GC.Collect();
                    comm.Dispose();
                }
            }

有什么想法或建议吗?

更新1

我将其更改为使用 using 语句,仍然泄漏。

最佳答案

using (var connection = new OdbcConnection(csb.ConnectionString))
{
    connection.Open();
    using (var command = new OdbcCommand("SELECT * FROM Tabl", connection))
    using (var reader =  command.ExecuteReader())
    {
        for (var count = 0; (count < 5 && reader.Read()); ++count)
        {
            //Read
        }
    }
}
OdbcConnection.ReleaseObjectPool();

上述代码中不存在内存泄漏,除非是在“//Read”执行点创建的。 GC.Collect 永远不应该在生产中使用;它很可能无论如何都没有帮助,并且实际上可能会阻碍 GC,因为它是自调整的。获取一个分析器(或免费试用版),例如 ANTS Memory Profiler看看你的物体上挂着什么。

Do not trust the Windows Task Manager to show you whether you have leak 。确保为此目的使用探查器。

关于c# - 在 C# .NET 中清理 ODBC DSN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1329354/

相关文章:

c# - 在 C# 中处理矩阵时的多维或锯齿状数组?

c# - RESTful 网络服务

javascript - 数据表 - DOM 源对象数组不会加载数据

c++ - C++程序中按映射结构的内存使用情况

linux - "Cannot allocate memory"尽管免费报告 "available"

Java清除集合不释放堆

java - Kotlin 中的哪些语言功能可能导致内存泄漏?

java - Java 中字符串的垃圾回收是如何进行的?

c# - 如何将数据从 MQL4 传递到 C# DLL

c - 如何在 struct 内部和 main 外部分配内存?