我正在使用 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/