开发者

Controls and Threads

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);
            }

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 a开发者_JS百科round this? How can I add this control to a flowtable in a new thread?


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.

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

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...
}

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜