Reputation: 664
Can anybody explain me, how can I create WPF Window in BackgroundWorker thread without errors?
I have some class (WPF Window):
public partial class Captcha : Window
{
public Captcha()
{
InitializeComponent();
}
private void SendCaptchaBtn_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
this.Close();
}
}
In backgroundworker's DoWork-function I trying to create an object with this Window:
BackgroundWorker bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerAsync();
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
parser = new Parser();
parser.ParseFunc(tempKeywords);
}
The Parser object has an "Captcha" Window:
Captcha captcha_dlg = new Captcha();
When I run program, I have runtime error at constuctor of Captcha-class point: The calling thread must be STA, because many UI components require this. What's wrong? Thansk for helping and sorry for my bad english :(.
Upvotes: 2
Views: 3703
Reputation: 30418
The short answer is, you can't.
Any threads used by BackgroundWorker
are MTA threads, because they come from the thread pool. There is no way to change a thread from MTA to STA after it is started.
If you want to create UI on another thread, your best bet is to use the Thread class, and set it to STA before startup by calling SetApartmentState().
Upvotes: 4