跨线程操作无效:控制'webForm'从其创建的线程以外的线程访问

G d*_*oid 0 c# multithreading winforms

我知道这个问题在这里被问了太多次,但我似乎没有修复它所以我发布了一个新问题.

我有两种形式Form1和Form2.Form2 通过将其最顶层属性设置为true,在form1上显示为叠加层.我有一个类为form1处理事务,如果找到所需的值,它会在STA线程中打开form2作为form1上的叠加层.

但是,如果在接下来的几秒钟内找不到该值,则类处理是一个连续的过程,然后我需要关闭已经打开的form2,由于上述异常,我目前无法做到这一点.

这是我的代码:

private void runBrowserThread(bool markerFound)
{
    try
    {
        var th = new Thread(() =>
        {
            if (markerFound == true)
            {
                if (Application.OpenForms.OfType<webForm>().Count() == 0)
                {
                    webForm frm = new webForm();
                    frm.Show();
                }

                Application.Run();
            }
            else
            {
                if (Application.OpenForms.OfType<webForm>().Count() == 1)
                {
                    Form fc = Application.OpenForms["webForm"];

                    if (fc != null)
                        fc.Close(); //**This line causes cross thread exception**
                }
            }
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start(); 
    } catch (Exception) 
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

任何建议都会非常感激.

use*_*107 5

如果你不知道自己在做什么,请不要使用线程!

用.替换错误行

    fc.Invoke(new MethodInvoker(delegate { fc.Close(); }));
Run Code Online (Sandbox Code Playgroud)

这将修复您的错误,但您正在完全混合您的工作和UI线程,这将给您更多的错误.