In the program, the camera should display everything that happens online without recording information, for this I use the AForge.Video and AForge.Video.DirectShow libraries from Aforge.net. When viewing the task manager, I noticed that when the camera is turned on, the application starts to have memory until a certain moment (as I understand, images from the stream are accumulated), then the memory is reset, apparently by the CLR, then again everything is new. And now the question: how to clean up the accumulated information from the stream independently without the help of the CLR? Code example:

private FilterInfoCollection videoDevices = null; private VideoCaptureDevice videoSource = null; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString); videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame); videoSource.Start(); } void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs) { this.pictureBox1.Image = (Image)eventArgs.Frame.Clone(); } 
  • how to make the information flow through without being saved somewhere, as is the case with the camera on the phone, when you simply turn it on and point to something, or as when setting up a camera in Skype, for example: it works ( you see yourself), but the information is simply displayed and "gone" - Maks

1 answer 1

Memory allocation in managed platforms is cheap, cleaning is expensive. Therefore, while there is free memory, it is consumed. As it becomes small, the garbage collector wakes up and cleans it. Therefore, what you see in the task manager is normal behavior.

In general, do not interfere with the work of the memory management system (garbage collector) in .NET. However, if you really want to, you can call the GC.Collect method.

In addition to memory consumption (which is a lot), the more acute issue is the consumption of unmanaged resources (which are few), such as handles. It is necessary to take care of their timely release.

In your code, it might look something like this:

 void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs) { //if (pictureBox1.Image != null) pictureBox1.Image.Dispose(); this.pictureBox1.Image = (Image)eventArgs.Frame.Clone(); } 

Note that calling Dispose in general does not free memory, it frees resources (handles)!

PS The original Frame image also needs to be removed. Since it is cloned, I assume that it is used elsewhere. After use, call Dispose . Or maybe cloning is not necessary?

  • The videoSource_NewFrame event itself disposit Image after returning from the handler, so cloning is needed. (The spirit raised the question) - MSDN.WhiteKnight