使用localdb进行NUnit测试期间的System.OutOfMemoryException

时间:2017-03-13 10:13:49

标签: c# sql-server nunit

在调试一些NUnit测试时,我们在通过脚本文件将行插入localdb时发现内存泄漏。这已经开始导致System.OutOfMemoryException,它阻止我们在开发过程中运行单元测试。

代码如下所示:

public static void InsertFromScriptFile (string conString, string dbName, string filePath)
{
   using (SqlConnection conn = new SqlConnection(string.Format(conString, dbName)))
   {
      string script = File.ReadAllText(filePath);

      using (SqlCommand cmd = new SqlCommand(script, conn))
      {
         try
         {
              conn.Open()
              cmd.ExecuteNonQuery();
         }
         catch (Exception ex)
         {
            Debug.WriteLine(ex);
            throw ex;
         }
         finally
         {
            conn.Close();
         }
      }
   }
}

当单步执行代码时,我得到了这些堆值:

Heap memory step-through

其中:

1) right after entering the inner try/catch
2) is after conn.open
3) is after cmd.ExecuteNonQuery
4) is after the conn.Close in the finally block

在我们的查询中,我们在数据库中插入了几行。在我们开始将文档作为base64字符串插入后,我们开始收到这些错误。

在大约10次测试后检查堆中的对象时,似乎TdsParserStateObject正在增长,以及对文档对象的引用。

TdsParserStateObject

在每个TestFixture之后,我们删除localdb并创建一个新的。我们预计gc会在某些时候回收内存,但它会不断增长。有没有人知道为什么记忆没有被回收?

1 个答案:

答案 0 :(得分:0)

找到了解决方法。我们跟踪了为我们为每个需要种子的测试创建的localdb实例分配的内存。这些实例以测试用例命名。当我们将它们全部重命名为相同名称并按顺序运行测试时(因此测试不会相互干扰)仅为单个实例分配内存。