Fix System.OutOfMemoryException during NUnit tests with localdb

While debugging some NUnit tests, we found a memory leak when inserting lines into localdb through a script file. This started to throw a System.OutOfMemoryException, which stops us from running unit tests during development.

The code is as follows:

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 navigating through the code, I get these heap values:

Step by step memory

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 began to embed documents as base lines, we began to receive these errors.

When checking objects on the heap after 10 tests, it seems that TdsParserStateObject is growing, as well as links to our document objects.

TdsParserStateObject

After each TestFixture, we discard localdb and create a new one. We expected gc to fix the memory at some point, but it continues to grow. Does anyone know why memory is not recovered?

+1
source share
1 answer

Workaround detected. We tracked the memory allocation for localdb instances that we created for each test for which we needed seed. These specimens were named after test cases. When we renamed all of them to the same name and ran the tests sequentially (so that the tests did not interfere with each other), memory was allocated for only one instance.

0
source

Source: https://habr.com/ru/post/1246142/


All Articles