Search code examples
c#multithreadingvideo-streamingrtspdispose

dispose my object in thread to get efficient memory usage


I am using Accord.Net to show RTSP video stream in a worker thread as you can see :

Main_Form:

     VideoFileReader reader = new VideoFileReader();
     Thread Proceso1;
     Proceso1 = new Thread(new ThreadStart(updateui));
     Proceso1.Start();

And my function :

public void updateui()
      {
               reader.Open(RTSPAddress);

                while (true)
                {
                    Bitmap frame1 = reader.ReadVideoFrame();

                    pictureRTSP.BackgroundImage = frame1;
                }
        }

It works fine for some seconds but after that i get out of memory exception .So i want to know how can i dispose all object in thread?


Solution

  • Every iteration of the while loop is creating a new bitmap, but they are not being explicitly destroyed. Every time you read a frame and update the display, you need to dispose of the previous frame:

    public void UpdateUI() // C# naming conventions
    {
        reader.Open(RTSPAddress);
        while (true)
        {
            Bitmap previousFrame = pictureRTSP.BackgroundImage;
            Bitmap currentFrame = reader.ReadVideoFrame();
            pictureRTSP.BackgroundImage = currentFrame;
            if (previousFrame != null)
                previousFrame.Dispose();
        }
    }
    

    This should help, but there's still some other issues that you need to work out:

    • What happens if an exception is thrown while trying to read the next frame?
    • What happens when you reach the end of the video stream?
    • What happens if the code above runs faster than the frame rate of the video?