另一个线程更新图形用户界面 - WPF Powershell

3

我之前问过这个问题,但我仍然有些困惑。真的希望能得到一些帮助。我只需要能够从后台任务向我的Rich TextBox添加文本即可。如果我删除Start-Job -ScriptBlock { },则在GUI线程上更新良好。我该怎么做才能从Start-Job更新我的richtextbox?

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

"Start-Job" 使用另一个进程而不仅仅是另一个线程。 - user4003407
http://learn-powershell.net/2013/04/19/sharing-variables-and-live-objects-between-powershell-runspaces/ - Jaqueline Vanek
如果它创建自己的进程,有没有办法只创建一个后台线程?我在想类似于 C# 中的后台工作者。 - Rickybobby
刚刚阅读了这篇文章,看起来运行空间池可能是正确的选择。 - Rickybobby
1个回答

1

我不是WPF中PowerShell的重度用户,但根据我理解你的帖子,我认为我仍然可以提供帮助。

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();
     }

我相信这应该可以工作,但你需要尝试一下。以上是访问最初创建RTF框的主分派线程的最佳方法。尝试一下,如果还不起作用,请告诉我。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接