You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++/CLI代码内存泄漏求助:ODBC查询致内存持续上涨

内存泄漏排查:ODBC循环查询中的ULPersonTable强引用问题

我最近在运行一段循环执行ODBC查询的代码时,遇到了顽固的内存泄漏问题,测试代码如下:

static void Main(string[] args) { 
    String connectionString = "DSN=DotNetUltraLightDSII; UID=user; PWD=pass"; 
    String query = "select * from person"; 
    using (OdbcConnection connection = new OdbcConnection(connectionString)) { 
        connection.Open(); 
        for (Int32 trial = 1; trial <= 100000; trial++) { 
            if (0 == trial % 1000) { 
                Console.WriteLine("Executing trial #{0:#,0}", trial); 
                GC.Collect(); 
            } 
            using (OdbcCommand command = new OdbcCommand(query, connection)) { 
                using (OdbcDataReader reader = command.ExecuteReader()) { 
                    do { 
                        while (reader.Read()) { 
                            for (Int32 colIndex = 0; colIndex < reader.FieldCount; colIndex++) { 
                                Object x = reader[colIndex]; 
                                IDisposable d = x as IDisposable; 
                                if (null != d) { 
                                    d.Dispose(); 
                                } 
                                d = null; 
                                x = null; 
                            } 
                        } 
                    } while (reader.NextResult()); 
                    reader.Close(); 
                } 
            } 
        } 
        connection.Close(); 
    }
}

核心问题

  • 内存占用随循环次数持续上升,即使手动调用GC.Collect()也无法有效释放内存
  • 通过堆分析发现存在大量指向ULPersonTable的强引用,但完全找不到这些引用的具体来源
  • 从业务逻辑判断,相关实例本该被销毁,我也已将该类型实例记录在gcroot中,但内存始终无法回收

补充信息:内存占用趋势图显示持续攀升,堆快照对比可见ULPersonTable实例未被正常回收

内容的提问来源于stack exchange,提问作者sid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:46:03