在 winform 应用程序中关闭表单时如何修复 "System.ObjectDisposedException"

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

我想使用 openTK 在 openGL 中播放视频。它工作正常。但是在关闭该特定表单时,它会在代码 "while (glControl1.IsIdle)" 下抛出异常 "System.ObjectDisposedException: 'Cannot access a disposed object.'"。我该如何解决? 我的应用包含 'Form1'。当用户单击其上的按钮时,'Form2' 将作为新的 window 打开。此 Form2 将在 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();           
    }

如何检查它是否已处置?:

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

假设它继承自 WinForms Control class,它应该实现 IsDisposed.

试试这个是否可行。

    private void Application_Idle(object sender, EventArgs e) { 
    try {while (glControl1.IsIdle) 
{ 
Render(); 
} 
    }
    Catch(Exception ex)
    //print the ex
    }