如何从单独的线程向容器添加控件 [英] How Do I Add Control To Container From Separate Thread

查看:114
本文介绍了如何从单独的线程向容器添加控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从异步线程向flowlayoutpanel添加一些控件,但是得到一个错误,上面写着跨线程操作无效:控件'ect'从其创建的线程以外的线程访问。 。

请帮帮我



来自意大利的Antonio

Hi, i want to add some controls to flowlayoutpanel from async thread, but di get an error that say "Cross-thread operation not valid: Control 'ect' accessed from a thread other than the thread it was created on.".
Please help me

Antonio from italy

推荐答案

错误:跨线程操作无效:从线程访问控制'listView1'除了创建它的线程外。 [ ^ ]



http://stackoverflow.com/questions/5037470/cross-thread-operation-not-valid [ ^ ]



阅读本文 [ ^ ]
ERROR : Cross-thread operation not valid: Control 'listView1' accessed from a thread other than the thread it was created on.[^]

http://stackoverflow.com/questions/5037470/cross-thread-operation-not-valid[^]

Read This[^]


它相对简单,你必须在UI线程上调用添加/删除/修改控件:



Its relatively simple, you have to invoke the adding/removing/modifying of a control on the UI thread:

flowLayoutPanel1.Invoke((MethodInvoker) delegate {
    //Code to add your control to the panel here.
});





您可以在调用之外构造控件,并且只将add添加到调用委托中。这只是其中一种方式,还有其他方法。例如,在调用flowLayoutPanel1.Invoke之前,您应首先检查是否确实会发生跨线程操作,方法是检查flowLayoutPanel1.InvokeRequired的值。如果这是真的,那么执行上述操作,如果没有,只需将其直接添加到面板中。



You can construct the control outside of the invoke, and only put the add inside the invoke delegate. This is just one way of doing it, there are other ways. For example, before calling flowLayoutPanel1.Invoke you should check first if a cross-thread operation will really occur by checking the value of flowLayoutPanel1.InvokeRequired. If that is true, then do the above, if not, just add it directly to the panel.


这篇关于如何从单独的线程向容器添加控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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