Memory Leak in C#

memory leak in c# reading data from sql database

I suspect that Entities is a class generated by Entity Framework and inherited from DbContext. If so try to use using block:

using(var entities = new Entities())
{
...
entities.SaveChanges();
}

Please note that in general it is not the perfect solution to initiate a new instance of DbContext for every single request. For details see this great answer.

C# memory leak?

but to be sure I ensure I dispose any objects after using them

Dispose() is not directly related to memory management or leaks.

You'll have to look for unused objects that are still 'reachable'. Use a memory-profiler to find out.

You can start with the free CLR-Profiler.

What are ways to solve Memory Leaks in C#

C#, the .NET Framework uses Managed Memory and everything (but allocated unmanaged resources) is garbage collected.

It is safe to assume that managed types are always garbage collected. That includes arrays, classes and structures. Feel free to do int[] stuff = new int[32]; and forget about it.

If you open a file, database connection, or any other unmanaged resource in a class, implement the IDisposable interface and in your Dispose method de-allocate the unmanaged resource.

Any class which implements IDisposable should be explicitly closed, or used in a (I think cool) Using block like;

using (StreamReader reader = new StreamReader("myfile.txt"))
{
... your code here
}

Here .NET will dispose reader when out of the { } scope.



Related Topics



Leave a reply



Submit