Search code examples
c#filesystemwatcher

Out of memory exception caused by FileSystemWatcher


I am trying to load an image and performing some process on it each time when an new image was create in a folder. The code ran fine in the debugging mode. However, when I copied the executable folder to the target machine. The FileSystemWatcher threw out an exception of "out of memory" every time. The .jpg is only 60KB. The code is written in C#.

Could anyone help me on this? Thank you.

private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
   try
   {
       source = new Image<Gray, byte>((Bitmap)Bitmap.FromFile(e.FullPath));
       frame = source.ThresholdBinary(new Gray(180), new Gray(255));
   }
   catch (Exception ex)
   {
       MessageBox.Show("File Loading Failed: " + ex.Message);
   }
}

A stack trace is here:

.ctor at offset 342 in file:line:column :0:0

Main at offset 59 in file:line:column :0:0


Solution

  • Your problem is that you're replacing your source Bitmap instance on each call to fileSystemWatcher_Created without disposing of the previous instance. Bitmap objects are wrappers around unmanaged GDI+ resources, and must be explicitly disposed when you're no longer using them. The same will apply to your frame object. The code below adds explicit disposal to your event handler. Note that I'm locking to avoid threading problems.

    try
    {
        lock (fileSystemWatcher)
        {
            var oldSource = source;
            var oldFrame = frame;
    
            source = new Image<Gray, byte>((Bitmap)Bitmap.FromFile(e.FullPath));
            frame = source.ThresholdBinary(new Gray(180), new Gray(255));
    
            if (oldSource != null)
                oldSource.Dispose();
    
            if (oldFrame != null)
                oldFrame.Dispose();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("File Loading Failed: " + ex.Message);
    }