将面板添加到不同线程上的表单 [英] adding Panel to form on different thread

查看:71
本文介绍了将面板添加到不同线程上的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个面板,其中包含一个活动的x组件以显示摄像机流.这是外部代码.此面板只能由于相机驱动程序而运行STA线程.

I have a panel that contains a active x component to show a camera stream. this is external code. this panel can only be run a STA thread becouse of the camera driver.

如何在另一个线程创建的表单上显示此面板? 例如:

how can i show this panel on a form created on another thread? for example:

[STAThread]
        public Main()
        {

            Panel display = new Panel();

            Thread form = new Thread(()=>
            {
                Form displayForm = new Form();
                displayForm.Show();
                displayForm.Controls.Add(display);
            });
            form.Start();

            CameraComponent axCamera = new CameraComponent(); //create new camera component active x component
            display.Controls.Add(axCamera);
        }

但是这会引发以下异常:display.Controls.Add(axCamera); 例外:跨线程操作无效:从其他线程(不是在其上创建线程的那个线程)访问的控件.

But this throws an exception on : display.Controls.Add(axCamera); exception: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

推荐答案

您必须调用该操作:

Thread form = new Thread(()=>
{
    Form displayForm = new Form();
    displayForm.Show();
    display.Invoke((MethodInvoker)delegate { displayForm.Controls.Add(display); });
});

老实说,我看不出您想要这样做的任何理由.这是非常简单且快速的操作,您应该在UI线程上执行此操作,而不是创建新线程.

and to be honest I do not see any reason why you would want to do that. It is very simple and fast operation and you should do it on UI thread instead of creating new one.

这篇关于将面板添加到不同线程上的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆