为什么我的powershell GUI滞后?

时间:2016-01-06 17:52:31

标签: user-interface powershell runspace

我正在尝试学习如何使用powershell运行空间实时更新GUI。我这里有一个简单的小代码,它从1到50开始循环并将它们输出到GUI上的文本框。 GUI没有锁定但是它非常滞后。如果我尝试在空白文本框中键入文本,状态框将停止更新或缓慢更新。我是否需要以某种方式更改我的代码以加快此过程?

$Global:GuiHash = [hashtable]::Synchronized(@{})
$GuiRunspace =[runspacefactory]::CreateRunspace()
$GuiRunspace.ApartmentState = "STA"
$GuiRunspace.ThreadOptions = "ReuseThread"          
$GuiRunspace.Open()
$GuiRunspace.SessionStateProxy.SetVariable("GuiHash",$Global:GuiHash)

$psCmd = [PowerShell]::Create().AddScript({


$inputXML = @"
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        mc:Ignorable="d"
        Title="GUI" Height="448.05" Width="656.017" ResizeMode="NoResize">
    <Grid Margin="0,0,-6.8,-0.8" Background="#FFD7D7D7">
        <Grid.RowDefinitions>
            <RowDefinition Height="403*"/>
            <RowDefinition Height="18*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Button x:Name="exitbtn" Content="Exit" HorizontalAlignment="Left" VerticalAlignment="Top" Width="135" Margin="447,365,0,0" Height="38" RenderTransformOrigin="0.489,0.462"/>
        <Label x:Name="label" Content="Label" HorizontalAlignment="Left" Margin="92,113,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.064,0.601" Height="26" Width="68"/>
        <TextBox x:Name="passwordBox" Margin="167,113,0,0" VerticalAlignment="Top" Height="24" HorizontalAlignment="Left" Width="136"/>
        <TextBox x:Name="stsbox" HorizontalAlignment="Left" Height="62" Margin="67,267,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="300" Background="#FFDADADA" Foreground="Black" Opacity="0.45" SelectionBrush="#FF1D6EBF" RenderTransformOrigin="0.503,-0.59" IsReadOnly="True"/>
    </Grid>
</Window>
"@ 
$inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^<Win.*', '<Window'

$Global:GuiHash.window=[Windows.Markup.XamlReader]::Parse($inputxml)
$Global:GuiHash.stsbox = $Global:GuiHash.window.findname('stsbox')

 $Global:GuiHash.Error = $Error
 $GuiHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $GuiRunspace
$handle = $psCmd.BeginInvoke()


Start-Sleep -Milliseconds 100

for ($z = 1; $z -le 50; $z++){
 $i = $z
 $GuiHash.stsbox.Dispatcher.Invoke([System.Action]{$Global:GuiHash.stsbox.text = "$i"},"normal")
 }

0 个答案:

没有答案