I am Eager to know how to do memory management in c# application.
My application is not releasing memory even I dispose objects and make it nullify. For testing purpose, I have created sample application as described below.
An application has two buttons 1) Consume Memory 2) Release Memory
By clicking on Consume Memory I am going to create and add 500 Memory Stream objects into List.
By clicking on Release Memory I am going to dispose all Memory Stream object and nullify that List too. and Collect garbage collection.
But when I start an application at that time my task manager will show me 8.6 MB Memory usage. When I press Consume Memory at that time task manager will show me 679.6 MB Memory Usage. When I Press Release Memory at that time task manager will show 680.0 MB Memory usage.
How can I forcefully release memory?
Code
public partial class MainWindow : Window
{
List<System.IO.MemoryStream> MemoryStreamCollection = new List<System.IO.MemoryStream>();
public MainWindow()
{
InitializeComponent();
}
private void ConsumeMemory_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 500; i++)
{
MemoryStreamCollection.Add(new System.IO.MemoryStream(System.IO.File.ReadAllBytes(@"D:\TestPDF.pdf")));
}
MessageBox.Show("Done");
}
private void ReleaseMemory_Click(object sender, RoutedEventArgs e)
{
foreach (System.IO.MemoryStream memoryStream in MemoryStreamCollection)
{
memoryStream.Dispose();
}
MemoryStreamCollection = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
MessageBox.Show("Done");
}
}
Screenshot when an application starts
Screenshot after consume memory button click.
Screenshot after release memory button click.