问题
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