ali seifi
ali seifi

Reputation: 3

multithreadin on gui in c#

i'm working on a project that contains multithreading on GUI here's my code in my form.cs file i use this code

    delegate void voidstringfunction(System.Drawing.Image x);

    public void ShowImage(System.Drawing.Image x)
    {

        if (pictureBox1.InvokeRequired)
            pictureBox1.Invoke(new voidstringfunction(ShowImage), x);

        pictureBox1.Image = x;
        pictureBox1.Update();

    }

    public void ThreadFunc(){
        SGSserverForm form2 = (SGSserverForm)(Application.OpenForms[0]);
        form2.ShowImage(tempImage);
    }
    //this event is running too
    void videoSource_NewFrameEvent(object sender, AForge.Video.NewFrameEventArgs eventArgs)
    {
        pictureBox5.Invoke(new MethodInvoker(() => pictureBox5.Image = tempIm));
    }

when i start thread, in program.cs file i get this exception "Object is currently in use elsewhere." on line that contains

sgsClientForm.ShowDialog();

what's the problem? thanks everyone

Upvotes: 0

Views: 63

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

You check whether you need to invoke, and Invoke if so. However, after invoking, you continue the method, performing the operation on the "non-GUI" thread anyway. Try this:

public void ShowImage(System.Drawing.Image x)
{
    if (pictureBox1.InvokeRequired)
    {
        pictureBox1.Invoke(new voidstringfunction(ShowImage), x);
        return;
    }

    pictureBox1.Image = x;
    pictureBox1.Update();
}

Upvotes: 1

Related Questions