Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.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
C# 跨线程UI-动态控件_C#_Multithreading_Winforms - Fatal编程技术网

C# 跨线程UI-动态控件

C# 跨线程UI-动态控件,c#,multithreading,winforms,C#,Multithreading,Winforms,我的WinForms应用程序需要一个加载面板。 我正在使用找到的示例 flowLayoutPanel1位于UI线程上,异步委托代码替换线程。示例中的睡眠与下面的代码类似。将动态控件添加到流面板时出现跨线程错误 AsyncProcessDelegate d = delegate() { flowLayoutPanel1.Controls.Clear(); Panel p1 = new Panel(); Button btn1 = new Button(); p1.Co

我的WinForms应用程序需要一个加载面板。 我正在使用找到的示例

flowLayoutPanel1位于UI线程上,异步委托代码替换线程。示例中的睡眠与下面的代码类似。将动态控件添加到流面板时出现跨线程错误

AsyncProcessDelegate d = delegate() {
     flowLayoutPanel1.Controls.Clear();

Panel p1 = new Panel();
Button btn1 = new Button();

        p1.Controls.Add(btn1);

        //tried to access from another thread
        flowLayoutPanel1.Controls.Add(p1);
        // Just in case it's not clear, I already know this does not work
        // The question is how can I make the example wait for my UI to load
        // if I can't do the dynamic control creation as shown.
  };

  RunAsyncOperation(d);

这不是一个好的做法,但这将明确地解决你的问题

this.Control.CheckForIllegalCrossThreadCalls=false;

您无法从另一个线程访问控件,这就是为什么会出现异常。这里的问题是什么?问题是如果我不能如图所示创建动态控件,如何让示例等待UI加载。我有一些想法,但我一直在苦思冥想,快到最后期限了。你希望你的UI加载是什么?上面的控件不需要等待。我如何让示例等待UI加载?这有点违背了异步的目的?@TreyPaschal-UI的创建速度非常快。如果你的速度很慢,那是因为你正在某处加载数据。也许您需要异步加载数据,并在加载后完成UI的呈现。这根本解决不了任何问题。这只是把你的头埋在沙子里。