You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从其他线程更新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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 04:04:56