首页 > 解决方案 > "Cross-thread operation not valid: Control 'form1' accessed from a thread other than the thread it was created on."

问题描述

I have a winforms project which has formA and formB. When formA loads, it calls class Calculation to do some logic and opens formB to display something. formA has a button to close formB. When I click the button to close formB, it give me an error:

"Cross-thread operation not valid: Control 'formB' accessed from a thread other than the thread it was created on."

List<Form> forms = new List<Form>();

formA_Load()
{
    DemoObject calfrmA = new DemoObject();
    calfrmA.getData();
}


public class DemoObject
{
    public void getData()
    {
         formB frmB = new frmB();
         frmB.Name = "frmB";
         forms.Add(frmB);
         frmB.Show();
    }
}

formA button click

public void button1_click()
{
       foreach(Form frm in forms)
       {
            if(frm.Name == "frmB")
            {
                 frm.Close();
            }
       }
}

the frm.Close() gives an error. How I can fix the issue? Please guide me. Thanks

Edited code: I have tried but still the same. DemoObject is a class.

formA_Load()
{
    foreach (DemoObject tobject in objectList.Values) {
                Thread thread = new Thread(delegate ()
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        tobject.getData();
                    }));
                });
                thread.Start();
            }
}

标签: c#multithreadingwinforms

解决方案


推荐阅读