Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create WPF controls in a background thread?

I have method which create background thread to make some action. In this background thread I create object. But this object while creating in runtime give me an exception :

The calling thread must be STA, because many UI components require this.

I know that I must use Dispatcher to make reflect something to UI. But in this case I just create an object and dont iteract with UI. This is my code:

    public void SomeMethod()
      {
         BackgroundWorker worker = new BackgroundWorker();
         worker.DoWork += new DoWorkEventHandler(Background_Method);
         worker.RunWorkerAsync();
      }

   void Background_Method(object sender, DoWorkEventArgs e)
      {
         TreeView tv = new TreeView();
      }

How can I create objects in background thread?

I use WPF application

like image 953
Polaris Avatar asked May 04 '10 06:05

Polaris


1 Answers

TreeView is a UI control. You can only create and manipulate UI controls on a UI thread, so what you're trying to do is not possible.

What you want to do is do all of the time-consuming work on the background thread, and then "call back" to the UI thread to manipulate the UI. This is actually quite easy:

void Background_Method(object sender, DoWorkEventArgs e)
{
    // ... time consuming stuff...

    // call back to the window to do the UI-manipulation
    this.BeginInvoke(new MethodInvoker(delegate {
        TreeView tv = new TreeView();
        // etc, manipulate
    }));
}

I may have got the syntax wrong for BeginInvoke (it's off the top of my head), but there you go anyway...

like image 112
Dean Harding Avatar answered Oct 07 '22 15:10

Dean Harding