如何在BackgroundWorker中创建WPF窗口?

发布于 2024-09-16 22:03:33 字数 959 浏览 7 评论 0原文

谁能解释一下,如何在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我做我的改变 2024-09-23 22:03:33

简短的回答是,你不能。

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().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文