如何从其他线程更新PowerShell GUI文本框?
问题与解决方案
我尝试了多种代码变体,但均未成功:GUI出现冻结,且文本框无法写入和更新。我不确定为何该线程操作仍会导致UI冻结(我曾在网上看到一些使用XAML同步哈希的示例,但不想采用)。以下是适用于所有控件的可行解决方案:
function getAllControls() { param( [System.Windows.Forms.Control]$ParentControl ) $controls = @() foreach ($control in $ParentControl.Controls) { $controls += $control if ($control.Controls.Count -gt 0) { $controls += getAllControls -ParentControl $control } } return $controls } $btnTest2_Click = { $controls = getAllControls -ParentControl $Form; $rs = [runspacefactory]::CreateRunspace([initialsessionstate]::CreateDefault2()) $rs.Open() $rs.SessionStateProxy.SetVariable('controls', $controls) $instance = [powershell]::Create().AddScript({ $listBox = $controls | where {$_.Name -eq "myListBox"} if ($listBox -ne $null) { [Console]::WriteLine($listBox.Name); } else { [Console]::WriteLine("listBox -eq null"); } $ran = [random]::new(); $ceiling = 10; $index = 0; while($index -lt $ceiling) { $ranNext = $ran.Next(); [Console]::WriteLine($ranNext); Start-Sleep 1 $listBox.Items.Add($ranNext); $index++; } }) $instance.Runspace = $rs; $instance.BeginInvoke(); }
旧代码示例
$helperThread = { for ($i = 0; $i -lt 10; $i++) { $form.Invoke([Action]{ $tbxTest2Box.Text = "$($i). Updated from helper thread!" [System.Windows.Forms.Application]::DoEvents(); }) Sleep -Seconds 1; } } # Start the helper thread $runspace = [runspacefactory]::CreateRunspace() $runspace.ApartmentState = "STA" $runspace.Open() $powershell = [powershell]::Create().AddScript($helperThread) $powershell.Runspace = $runspace $handle = $powershell.BeginInvoke() $powershell.EndInvoke($handle) $powershell.Dispose() $runspace.Close()
内容的提问来源于stack exchange,提问作者Bbb
相关产品推荐
相关产品推荐

