Rickybobby
Rickybobby

Reputation: 305

GUI update from another thread - WPF Powershell

I asked this question before, but I still am having issues. Really hoping I could have some assistance. all I need is to be able to add append text to my Rich TextBox from a background job. If I remove Start-Job -ScriptBlock { } it updates fine while on the GUI thread. What can I do in order to update my richtextbox from Start-Job?

 Start-Job -ScriptBlock{
   $richTextBox1.AppendText('++++++++++++++++')
   $richTextBox1.Dispatcher.Invoke([action]{
   $richTextBox1.AppendText('-------------')
   },"Normal")
 }

Upvotes: 3

Views: 1202

Answers (1)

JoeTomks
JoeTomks

Reputation: 3276

I'm not a massive user of Powershell within WPF however as I understand your post I think I can still help.

public void RunPowershell_Script()
      {
           Thread t = new Thread(new ThreadStart(
           delegate
              {

                 Start-Job -ScriptBlock{

                   this.Dispatcher.Invoke((Action)(() =>
                   {                   

                      //Any Element that you need to interact with variables
                      //or controls from the main application on the main
                      //dispatcher thread go here.

                      $richTextBox1.AppendText('++++++++++++++++')
                      $richTextBox1.AppendText('-------------')  

                   }));

                }

                  //Any final code can go here.

              }
            ));
           t.Start();
     }

I believe this should work but you would have to have a play around. the above is the best way to access the main dispatcher thread in which the RTF box was originally created. Give it a try and let me know if it still doesn't work.

Upvotes: 1

Related Questions