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
C# Base64 String to Jpeg Image
Nullable<Int> VS. Int? - Is There Any Difference
Change Route Collection of MVC6 After Startup
Creating Sine or Square Wave in C#
Cannot Close Excel.Exe After Interop Process
Visual Studio Debugging "Quick Watch" Tool and Lambda Expressions
How to Run a .Net Console Application in the Background
Windows.Forms.Timer or System.Threading.Timer
Navigation Property Should Be Virtual - Not Required in Ef Core
Create Bitmap from a Byte Array of Pixel Data
Observablecollection<> VS. List<>
How to Get the Child Windows of a Window Given Its Hwnd
Find Index of a Value in an Array
Execute Specified Function Every X Seconds