Search code examples
c#multithreadingvisual-studio-2010videoaforge

Can't refresh pictureBox via playing video using AForge


i open video file using AForge library

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog opd = new OpenFileDialog();

        if (opd.ShowDialog() == DialogResult.OK)
        {
            FileVideoSource videoSource = new FileVideoSource(opd.FileName);
            videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
            videoSource.Start();
        }
    }

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

        pictureBox1.Image = bitmap;
        pictureBox1.Refresh();
    }

but in line "pictureBox1.Refresh" i have an exception "Cross-thread operation not valid: Control 'pictureBox1' accessed from a thread other than the thread it was created on" what is this?


Solution

  • As the exception hints, Controls can only be manipulated from within the thread they were created on.

    Here you have the main UI thread where your Form and Control are created, and you have the video reader thread from AForge. The code running in video_NewFrame is on the reader thread and cannot directly call methods on the controls.

    See here for more details. You have to do something along these lines:

    private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
    
        this.Invoke((MethodInvoker)delegate
        {
            pictureBox1.Image = bitmap;
            pictureBox1.Refresh();
        });      
    }