Powershell 线程与 C# 线程

Powershell threading vs C# threading

在 C# 中,当我想创建一个调用函数的线程时,我只是这样做。

Thread t = new Thread(() => calledFunction());
t.Start();

我的目标是在 Powershell 中做同样的事情。没什么特别的,它的唯一目的是防止 GUI 冻结。但我就是找不到可行的解决方案。

目前,我只是想让运行空间做任何事情。 如果我把它放在按钮的点击事件中,什么也不会发生。

$Runspace = [runspacefactory]::CreateRunspace()
$PowerShell = [powershell]::Create()
$PowerShell.runspace = $Runspace
$Runspace.Open()

[void]$PowerShell.AddScript({

    $test = "test"
    Write-Host $test

})

$PowerShell.Invoke()

但是,如果我在脚本块中放置一个消息框,就可以正常工作。当某些事情有效而某些事情无效时,这让我感到非常困惑。

如果您有一项任务,您必须调用一个函数来完成一些工作并更新 GUI。您将如何在其自己的线程中调用该函数,以便 GUI 在 Powershell 中工作时不会冻结?在 C# 中,我有上面发布的简单示例或使用 BackgroundWorker。

If I put this inside a click event of a button

$PowerShell.Invoke() 执行 同步 ,因此根据定义它将 阻塞 直到您添加的脚本完成,因此它 冻结 GUI。

nothing happens.

Write-Host $test(在PSv5+中)写入信息流(流号6),即不是.Invoke() 调用直接返回 - 只有 成功输出 (流编号 1)是;参见 about_Redirection

此外,即使有成功输出,从事件处理程序输出到成功流也将显示在控制台中(终端)。


If you had a task where you had to call a function that does some work and updates a GUI. How would you go about calling that function in its own thread so that the GUI won't freeze while it's working in Powershell?

参见以下内容,可以相对轻松地适应 WinForms。