Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 尽管使用了Invoke(),但未解决跨线程问题_Multithreading - Fatal编程技术网

Multithreading 尽管使用了Invoke(),但未解决跨线程问题

Multithreading 尽管使用了Invoke(),但未解决跨线程问题,multithreading,Multithreading,我的C#应用程序有很多表单来执行各种任务。为了简单起见,我有一个静态类formscolection,其中保存了其他每个表单的实例,以便在一个地方显示和隐藏它们 现在我得到了经典。我尝试用以下方法修复它: public class FormsCollection : Control // inherited from Control only to be // able to call "this.Invoke" {

我的C#应用程序有很多表单来执行各种任务。为了简单起见,我有一个静态类
formscolection
,其中保存了其他每个表单的实例,以便在一个地方显示和隐藏它们

现在我得到了经典。我尝试用以下方法修复它:

public class FormsCollection : Control // inherited from Control only to be
                                       // able to call "this.Invoke"
{
    public delegate void ShowFormDelegate(Form form);

    public static Main mainForm;
    // and many other forms...

    public void ShowForm(Form form)
    {
        if (form.InvokeRequired)
        {
            ShowFormDelegate delegateFunc = new ShowFormDelegate(ShowForm);
            this.Invoke(delegateFunc, new object[] { form });
        }
        else
        {
            previousForm = currentForm;

            currentForm.Hide();
            currentForm = form;
            currentForm.Show();
        }
    }
}
在用户/调用方表单中,我只需创建一个
formscolection
对象,并调用
ShowForm
方法(几乎有100个这样的调用):

在经历了所有这些磨难之后,我得到的是,同样的错误出现在和以前一样的地方!多么讽刺啊!:)
我做错了什么?请帮帮我……

我很难找到这个问题的答案。以下是任何正在努力解决此问题的程序员的更新代码:

public void Show(Form nextForm)
    {
        Thread thread = new Thread(
        new ThreadStart(() =>
        {
            PreviousForm.BeginInvoke(
                new Action(() =>
                {
                    PreviousForm = CurrentForm;
                    CurrentForm = nextForm;

                    PreviousForm.Hide();
                    CurrentForm.Show();
                }
            ));
        }
        ));

        thread.Start();
    }

这似乎解决了我所面临的跨线程问题,尽管有一些解决方法。它目前正在工作,没有引发任何异常,我已经测试了我的应用程序在不同表单之间来回运行的几乎所有场景。

我从不同的角度调试了我的应用程序,并得到了以下信息:
附加信息:在创建窗口句柄之前,不能对控件调用Invoke或BeginInvoke。
代码行:
this.Invoke(delegateFunc,新对象[]{form})
public void Show(Form nextForm)
    {
        Thread thread = new Thread(
        new ThreadStart(() =>
        {
            PreviousForm.BeginInvoke(
                new Action(() =>
                {
                    PreviousForm = CurrentForm;
                    CurrentForm = nextForm;

                    PreviousForm.Hide();
                    CurrentForm.Show();
                }
            ));
        }
        ));

        thread.Start();
    }