简体   繁体   中英

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:

    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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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