4

I'm playing around with using runspaces in PowerShell to enhance performance of a small GUI application.

What I've got so far is a runspace that has 2 purposes: First, it holds all my other runspaces and second, it parses my GUI xml file and displays it. It also adds the nodes to a sychronized hashtable, so I have it accessible across all runspaces. As you can imagine I have some buttons in this GUI which trigger actions when clicked; pretty simple stuff and actually it's working great so far. I can exchange data between the runspaces and I am also able to update the GUI when a certain button is clicked.

However, I am not able to call the addChild() method on an empty stackpanel in my xml file. What I basically want to do is just to add checkboxes to the stackpanel (named "CheckboxViewer").

$checkbox = New-Object System.Windows.Controls.CheckBox
$checkbox.Content = "Hello world"
$syncHash.checkbox = $checkbox
$syncHash.CheckboxViewer.Dispatcher.Invoke(
     [Action]{
         #this is working:
         $syncHash.CheckboxViewer.Background = 'Black'
         #this is not working
         $syncHash.CheckboxViewer.AddChild($syncHash.checkbox)
     }, "Normal")

The error message I receive is the typical error message one gets when trying to access another runspace directly (without using the dispatcher):

Exception calling "AddChild" with "1" argument(s): "The calling thread cannot access this object because a different thread owns it.

Any ideas what I am doing wrong here? Any kind of help would be much appreciated, thanks!

Quhalix89
  • 129
  • 1
  • 2
  • 10

1 Answers1

1

Try with this :

$syncHash.Window.Dispatcher.Invoke([action]{
    $checkbox = New-Object System.Windows.Controls.CheckBox
    $checkbox.Content = "Hello world"
    $syncHash.CheckboxViewer.AddChild($checkbox)
}, "Normal")

To add a control, you must declare it inside the [action]

Manu
  • 1,685
  • 11
  • 27