views:

28

answers:

1

Hello guys! 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 :(.

+2  A: 

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

Andy
Thanks, now it working :). This is optimal solution - for each asynch. function/process in my program to create an another thread?And what about the Dispatcher? It like MethodInvoker and delegates in Windows Form Applications and may be need, for example, for accessing to some controls in main Window? :)
Dmitriy
@Dmitriy If you're asking if it's optimal to create a new thread for each asynchronous thing your program is doing, I don't see another way if you want to show UI on that thread, since WPF must run on a STA thread.
Andy
Having two windows on the same thread is not really a big issue, since the heavy lifting is usually done on asyncronously (on another thread)
JoshVarga