使用PowerShell中的Task类

9

我正在尝试在Powershell中使用Task类来异步运行操作。但是我遇到了以下异常:

Id                     : 1
Exception              : System.AggregateException: One or more errors occurred. ---> System.Management.Automation.PSInvalidOperationException: There is no Runspace available to
                         run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script
                         block you attempted to invoke was:  Write-Host "hey!"
                            at System.Management.Automation.ScriptBlock.InvokeAsDelegateHelper(Object dollarUnder, Object dollarThis, Object[] args)
                            at System.Threading.Tasks.Task.Execute()
                            --- End of inner exception stack trace ---
                         ---> (Inner Exception #0) System.Management.Automation.PSInvalidOperationException: There is no Runspace available to run scripts in this thread. You can
                         provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was:
                         Write-Host "hey!"
                            at System.Management.Automation.ScriptBlock.InvokeAsDelegateHelper(Object dollarUnder, Object dollarThis, Object[] args)
                            at System.Threading.Tasks.Task.Execute()<---

Status                 : Faulted
IsCanceled             : False
IsCompleted            : True
CreationOptions        : DenyChildAttach
AsyncState             :
IsFaulted              : True
AsyncWaitHandle        : System.Threading.ManualResetEvent
CompletedSynchronously : False

我的代码:

$delegate = [System.Action]{ Write-Host "Test" }
[System.Threading.Tasks.Task]::Run($delegate)
2个回答

4

要让PowerShell与Task配合工作需要做很多工作,因为Task是一个比较底层的结构,不适合与PowerShell直接配合使用。

要异步执行PowerShell操作,请使用jobs


3
运行空间的实现更加棘手,但可以更高效。 - user2871239
不幸的是,看起来runspaces已经损坏了,因为每个调用都是顺序运行而不是并行运行。如果有人能够将ScriptBlock转换为lambda,我更喜欢使用Tasks。https://github.com/PowerShell/PowerShell/issues/3651 - Brain2000

1
Install-Module PSRunspacedDelegate -Scope CurrentUser

$delegate = New-RunspacedDelegate([System.Action] { Write-Host "Test" })
$Task = [System.Threading.Tasks.Task]::Run($delegate)

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