简体   繁体   English

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

[英]System.OutOfMemoryException during NUnit tests with localdb

While debugging some NUnit tests we found a memory leak when inserting rows into a localdb via a script file. 在调试一些NUnit测试时,我们发现在通过脚本文件将行插入localdb时会发生内存泄漏。 This has started leading to System.OutOfMemoryException which stops us from running unit tests during development. 这已经开始导致System.OutOfMemoryException,它阻止我们在开发期间运行单元测试。

The code looks like this: 代码如下所示:

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();
         }
      }
   }
}

When stepping through the code I get these heap values: 单步执行代码时,我得到以下堆值:

Heap memory step-through 堆内存步进

Where: 哪里:

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

In our query we insert a couple of rows into the database. 在我们的查询中,我们在数据库中插入了几行。 After we started inserting documents as base64 strings we started getting these errors. 在我们开始将文档作为base64字符串插入后,我们开始收到这些错误。

When inspecting the objects in the heap after about 10 tests it seems as it's the TdsParserStateObject that's growing, as well as references to our document objects. 在大约10次测试之后检查堆中的对象时,似乎正在增长的TdsParserStateObject以及对文档对象的引用。

TdsParserStateObject TdsParserStateObject

After each TestFixture we drop the localdb and create a new one. 在每个TestFixture之后,我们删除localdb并创建一个新的。 We expected the memory to be reclaimed by gc at some point but it keeps growing. 我们预计gc会在某些时候回收内存,但它会不断增长。 Does anyone have any idea why the memory isn't reclaimed? 有没有人知道为什么不回收内存?

Found a workaround. 找到了解决方法。 We tracked the memory being allocated to the localdb instances we created for every test we needed a seed for. 我们跟踪了为我们为每个需要种子的测试创建的localdb实例分配的内存。 These instances were named after the test cases. 这些实例以测试用例命名。 When we renamed all of them to the same name and ran the tests sequentially (so the tests didn't interfere with each other) memory was only allocated for a single instance. 当我们将它们全部重命名为相同名称并按顺序运行测试时(因此测试不会相互干扰)仅为单个实例分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM