如何在BackgroundWorker中创建WPF窗口?
谁能解释一下,如何在BackgroundWorker线程中创建WPF窗口而不出现错误?
我有一些类(WPF窗口):
public partial class Captcha : Window
{
public Captcha()
{
InitializeComponent();
}
private void SendCaptchaBtn_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
this.Close();
}
}
在backgroundworker的DoWork函数中,我试图用这个窗口创建一个对象:
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);
}
解析器对象有一个“验证码”窗口:
Captcha captcha_dlg = new Captcha();
当我运行程序时,我在验证码类点的构造函数处出现运行时错误:调用线程必须是STA,因为很多UI组件都需要这个。 怎么了?感谢您的帮助,并对我的英语不好感到抱歉:(。
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 :(.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短的回答是,你不能。
BackgroundWorker
使用的任何线程都是 MTA 线程,因为它们来自线程池。线程启动后无法将其从 MTA 更改为 STA。如果您想在另一个线程上创建 UI,最好的选择是使用 Thread 类,并在启动前通过调用 SetApartmentState()。
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().