title: Using Dispatcher Invoke with a Runspace in Powershell
body: <p>I am trying to learn how to use a Runspace to pass values to a GUI. I have been tweaking the script written by Boe Prox, trying to understand how Dispatcher.Invoke works with a runspace and came across a very strange problem</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-css lang-css prettyprint-override"><code>$uiHash = [hashtable]::Synchronized(@{})
  $newRunspace =[runspacefactory]::CreateRunspace()
  $newRunspace.ApartmentState = "STA"
  $newRunspace.ThreadOptions = "ReuseThread"          
  $newRunspace.Open()
  $newRunspace.SessionStateProxy.SetVariable("uiHash",$uiHash)
  
  
            
  $psCmd = [PowerShell]::Create().AddScript({   
      $uiHash.Error = $Error
      [xml]$xaml = @"
      &lt;Window
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          x:Name="Window" Title="Initial Window" WindowStartupLocation = "CenterScreen"
          Width = "650" Height = "800" ShowInTaskbar = "True"&gt;
          &lt;TextBox x:Name = "textbox" Height = "400" Width = "600"/&gt;
      &lt;/Window&gt;
  "@
      $reader=(New-Object System.Xml.XmlNodeReader $xaml)
      $uiHash.Window=[Windows.Markup.XamlReader]::Load( $reader )
      $uiHash.TextBox = $uiHash.window.FindName("textbox")
      $uiHash.Window.ShowDialog() | Out-Null
  })
  $psCmd.Runspace = $newRunspace
  $handle = $psCmd.BeginInvoke()
  
  #-----------------------------------------
  
  #Using the Dispatcher to send data from another thread to UI thread
  Update-Window -Title ("Services on {0}" -f $Env:Computername)
  $uiHash.Window.Dispatcher.invoke("Normal",[action]{$uiHash.TextBox.AppendText('test')})</code></pre>
  </div>
  </div>
  </p>
  
  <p>If I were to use the last line of the script without the <code>Update-Window -Title ("Services on {0}" -f $Env:Computername)</code> I get a <code>you cannot call a method on a null-valued expression.</code> InvokeMethodOnNull error and the text is not appended. However, if I add <code>Update-Window -Title ("Services on {0}" -f $Env:Computername)</code> right above the Dispatcher.invoke line, I still get the error, but the textbox contains the appended text.</p>
  
  <p>What is the reason for this occurrence? I have tried so many ways to use the Dispatcher.Invoke to add content to textboxes but always end up with a <code>cannot call a method method on null</code> error without any success, but now adding some lines that reference the UI and calling the Dispatcher.Invoke seems to make it work.</p>