Hi all!

I have been having the hardest time trying to get memory to release from an application I am developing. I know I could have written the code below without the classes but I wanted to makes sure that I understood how to pass references and not values in C#.

If you look at the coments, you will see that the application is still holding onto the memory even through I have left the class that was using all of the memory. I have tried setting fileSorter = null, fileArray = null but that did not work either.

Can anyone tell me why I am not able to release memory back to the system?

using System;
 
namespace ConsoleApplication1
{
 class Class1
 {
  [STAThread]
  static void Main(string[] args)
  {
   // Mem in use by ConsoleApplication1: 6,320K   
   FileSorter fileSorter = new FileSorter();
   fileSorter.SortFile();
 
   // Mem in use by ConsoleApplication1: 564,176K
  }
 }
 public class FileSorter
 {
  public void SortFile()
  {
   string[] fileArray = null;
   FileHandler fileHandler = new FileHandler();
   StringHandler stringHandler = new StringHandler();
 
   // Mem in use by ConsoleApplication1: 6,408K   
   fileHandler.FileToArray(ref fileArray, @"c:\tmp\Really Big File.txt");
 
   // Mem in use by ConsoleApplication1: 561,084K
   // File being sorted is only 114,437K
   // I expected a memory usage of about 120,845K
   stringHandler.SortArray(ref fileArray);
 
   // Mem in use by ConsoleApplication1: 561,136K
   fileHandler.ArrayToFile(ref fileArray, @"c:\tmp\Really Big File Sorted.txt");
 
   // The file has now been sorted.  How do I dispose of fileArray properly before I leave this method?
  }
 }
 
 public class FileHandler
 {
  public void FileToArray(ref string[] outputArray, string filePath)
  {
   using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
   {
    outputArray = System.Text.RegularExpressions.Regex.Split(sr.ReadToEnd(), Environment.NewLine);
    sr.Close();
   }
  }
 
  public void ArrayToFile(ref string[] inputArray, string filePath)
  {
   using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
   {
    foreach (string inputLine in inputArray)
    {
     sw.WriteLine(inputLine);
    }
    sw.Close();
   }
  }
 }
 
 public class StringHandler
 {
  public void SortArray(ref string[] inputArray)
  {
   Array.Sort(inputArray);
  }
 }
}

If not, perhaps the

.Dispose();

method will dispose of it?

If not, perhaps the

.Dispose();

method will dispose of it?

That was my first thought, actually. But, then I found the using directive, and it looks like it does the Dispose() for you.

Keep in mind, I'm still somewhat new at C#, but there was some reason for including using rather than disposing it directly. I'll have to grab one of the books I've bought to figure out why...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.