Search code examples
c#winformsopenglopentkformclosing

How to fix "System.ObjectDisposedException" when closing a form in winform application


I want to play a video in openGL using openTK. It is working fine. but when closing that particular form it throws an exception "System.ObjectDisposedException: 'Cannot access a disposed object.'" under the code "while (glControl1.IsIdle)". How can I resolve it? My app contains a 'Form1'. When user clicks a button on it, a 'Form2' will open as new window. This Form2 will play video in openGL.

 private void Form2_Load(object sender, EventArgs e)
    {//openGL code
        StartCameras();
        glControl1.Resize += new EventHandler(glControl1_Resize);
        glControl1.Paint += new PaintEventHandler(glControl1_Paint);
        Application.Idle += Application_Idle;
        // Ensure that the viewport and projection matrix are set correctly.
        glControl1_Resize(glControl1, EventArgs.Empty);
    }
private void Application_Idle(object sender, EventArgs e)
    {
        while (glControl1.IsIdle)
        {
           Render();
        }
    }
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {        
        StopCameras();
    }
 private void StopCameras()
    {
        timer.Stop();
        videoSourcePlayer1.SignalToStop();
        videoSourcePlayer1.WaitForStop();           
    }

Solution

  • What about checking if it's disposed?:

    while (!glControl1.IsDisposed && glControl1.IsIdle)
    

    Assuming it inherits from the WinForms Control class, it should implement IsDisposed.