create Wpf user controls in other thread

拥有回忆 提交于 2019-12-08 06:49:45

问题


I am trying to create some UserControl(s) using another thread, and I am using code like this:

    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:

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.


回答1:


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.

In this case, just 3 controls, forget about Tasks and just do it directly, single-threaded.




回答2:


You can dispatch the operation of adding controls to the Children collection to the UI thread using Dispatcher:

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.



来源:https://stackoverflow.com/questions/4884802/create-wpf-user-controls-in-other-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!