使用 localdb 进行 NUnit 测试期间的 System.OutOfMemoryException [英] System.OutOfMemoryException during NUnit tests with localdb

查看:62
本文介绍了使用 localdb 进行 NUnit 测试期间的 System.OutOfMemoryException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While debugging some NUnit tests we found a memory leak when inserting rows into a localdb via a script file. This has started leading to System.OutOfMemoryException which stops us from running unit tests during development.

代码如下:

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:

堆内存步进

地点:

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 字符串插入后,我们开始收到这些错误.

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.

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

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.

TdsParserStateObject

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

After each TestFixture we drop the localdb and create a new one. We expected the memory to be reclaimed by gc at some point but it keeps growing. Does anyone have any idea why the memory isn't reclaimed?

推荐答案

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

Found a workaround. We tracked the memory being allocated to the localdb instances we created for every test we needed a seed for. 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.

这篇关于使用 localdb 进行 NUnit 测试期间的 System.OutOfMemoryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆