控件和线程 [英] Controls and Threads

查看:131
本文介绍了控件和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建新线程的按钮.该线程包含以下内容.

I have a button that creates a new thread. That thread contains the following.

foreach (DataRow r in results.Rows)
            {
                var item = new ResultItem(this)
                               {
                                   Image = r[1].ToString(),
                                   Video = r[2].ToString(),
                                   Title = r[3].ToString().Trim(),
                                   Duration = r[4].ToString().Trim()
                               };


                SearchFlow.Controls.Add(item);
            }

我收到此错误:在一个线程上创建的控件不能作为另一个线程上的控件的父级. ResItem是自定义用户控件,它是项目的一部分,而不是第三方控件.有没有解决的办法?如何在新线程中将此控件添加到流表中?

I get this error: Controls created on one thread cannot be parented to a control on a different thread. ResItem is custom usercontrol that's part of the project, not a 3rd party control. Is there a way around this? How can I add this control to a flowtable in a new thread?

推荐答案

您只能触摸创建控件的线程上的UI控件.这也意味着不能将由后台线程创建的任何控件添加到您的UI.

You must only touch UI controls on the thread that created them. This also means that any control created by a background thread cannot be added to your UI.

解决方案是仅使用UI(前台)线程创建控件.

The solution is to only create controls using the UI (foreground) thread.

执行此操作的一种方法是在窗体上创建一个方法来创建所需的控件,并检查它是否为前台线程.如果没有,它可以将自己调到前台.可以使用实现 ISyncronizeInvoke 的任何控件来完成此操作.

One way to do this is to have a method on the form that creates the controls you need, and have it check to see if it is the foreground thread. If not, it can marshal itself to the foreground. This can be done with any control that implements ISyncronizeInvoke.

private void Foo(object state)
{
    if (this.InvokeRequired)
    {
        this.Invoke(Foo, state);
        return;
    }
    // Do your creation of UI here...
}

请注意,此示例将阻塞后台线程,直到UI有一些时间来处理该方法为止.

Note that this example will block the background thread until the UI has some time to process the method.

这篇关于控件和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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