简体   繁体   English

在其他线程中创建Wpf用户控件

[英]create Wpf user controls in other thread

I am trying to create some UserControl(s) using another thread, and I am using code like this: 我正在尝试使用另一个线程创建一些UserControl,并且我正在使用如下代码:

    private void btnDemo_Click(object sender, RoutedEventArgs e)
    {
      Task tsk = Task.Factory.StartNew(() =>
      {
        for (int i = 0; i < 3; i++)
        {
          MyControl sprite = new MyControl();
          pnlTest.Children.Add(sprite);
        }
      });
    }

But I am getting this exception in the UserControl constructor: 但是我在UserControl构造函数中收到此异常:

The calling thread must be STA, because many UI components require this.

I am not sure that I am using the right approach to do this. 我不确定我是否使用正确的方法来执行此操作。 Please, Can you help me with this. 拜托,你能帮我这个忙吗?

thanks. 谢谢。

The creating of the controls can be done on any Thread but Adding them to the GUI needs to be synchronized to the main Thread. 可以在任何线程上完成控件的创建,但是将控件添加到GUI时需要与主线程同步。

In this case, just 3 controls, forget about Tasks and just do it directly, single-threaded. 在这种情况下,只需3个控件,就不必理会“任务”,而只需直接执行单线程操作即可。

You can dispatch the operation of adding controls to the Children collection to the UI thread using Dispatcher: 您可以使用Dispatcher分派将控件添加到UI线程的Children集合中的操作:

private void btnDemo_Click(object sender, RoutedEventArgs e)
{
  Task tsk = Task.Factory.StartNew(() =>
  {
    for (int i = 0; i < 3; i++)
    {
      Dispatcher.BeginInvoke(new Action(() => {
         MyControl sprite = new MyControl();
         pnlTest.Children.Add(sprite);
      }));
    }
  });
}

By calling BeginInvoke on Dispatcher you basically adding the operation to the queue to execute on the UI thread. 通过在Dispatcher上调用BeginInvoke,您基本上可以将操作添加到队列中以在UI线程上执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM