Form Closing上的System.ObjectDisposedException

时间:2016-03-26 00:09:31

标签: c# winforms aforge formclosing

我有一个C#WinForms应用程序,它使用AForge从文件流(fs)播放视频,这是使用字节数组(TheVideoInBytes)创建的。在视频流中创建视频后,它将使用“private void video_NewFrame”开始播放(private void tsbtnPlayPause_Click)。

以下是播放代码:

    private void tsbtnPlayPause_Click(object sender, EventArgs e)
    {

        if (tsbtnPlayStop.Text == "▶")
        {
            try
            {
                TheVideoInBytes = Convert.FromBase64String(glbstrVideo);
                System.IO.FileStream fs = new System.IO.FileStream("whatever", System.IO.FileMode.Create);
                fs.Write(TheVideoInBytes, 0, TheVideoInBytes.Length);
                videoSource.Source = "whatever";

                videoSource.Start();
                videoSource.PlayingFinished += VideoSource_PlayingFinished;
                tsbtnPlayStop.Text = "█";
                fs.Dispose();
                fs.Close();

                //videoSource.Source = ofd.FileName;
                videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
                tsbtnCloseMedia.Enabled = tsbtnPlayStop.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "oops.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        else
        {
            videoSource.SignalToStop();
            tsbtnPlayStop.Text = "▶";
            videoSource.Source = null;
            System.IO.File.Delete("whatever");
        }
    }

...这里是框架的代码:

    private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        try
        {
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();

            this.Invoke((MethodInvoker)delegate
            {
                pbVid.Image = bitmap;
                pbVid.Refresh();
            });
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString(), "oops.", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

问题:如果在播放过程中关闭主窗体(frmMain_FormClosing(对象发送方,FormClosingEventArgs e)),应用程序将崩溃并显示以下消息:

System.IO.IOException未处理   的HResult = -2147024864   Message =进程无法访问该文件,因为它正由另一个进程使用。

System.ObjectDisposedException无法访问已处置的对象。

此错误发生在private void video_NewFrame中的此行:

            this.Invoke((MethodInvoker)delegate

如何安全地删除此过程以及确切编写代码的位置?

0 个答案:

没有答案
相关问题