Memory leak using linqpad and linq2sql

I am executing very simple code in linqpad. And I do not understand where my memory is after execution. He just takes the memory and does not want to return it back.

var step = 200000; for (int i = 0; i < 1000; i++) { //WordStats is linq2sql entity (dataContext.WordStats) var keys = WordStats.Skip(step*i).Take(step).ToList(); GC.Collect(); } 
+4
source share
2 answers

LINQ DataContext caches all read objects in the DataContext, even if you do not have references to them. If you request the object later, you get a cached version.

Instead of executing GC.Collect() you should clear the caches in the LINQ context, here is a blog post describing how.

In short:

 const BindingFlags FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; var method = context.GetType().GetMethod("ClearCache", FLAGS); method.Invoke(context, null); 

In LINQPad, you should replace context with this .

+2
source

Another approach is to tell LINQ to SQL not to cache objects in the first place:

 this.ObjectTrackingEnabled = false; 
+1
source

All Articles