【问题标题】:Using the Task class in powershell在 powershell 中使用 Task 类
【发布时间】:2013-02-25 12:30:22
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

    标签: powershell asynchronous task runspace


    【解决方案1】:

    要让 PowerShell 与 Task 一起工作需要做很多工作。 Task 是一个太多的低级结构,PowerShell 无法直接使用它。

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

    【讨论】:

    • 运行空间更难实现,但可以是more performant
    • 不幸的是,看起来运行空间被破坏了,因为每个调用都是按顺序而不是并行运行的。如果有人可以将 ScriptBlock 转换为 lamda,我更喜欢使用 Tasks。 github.com/PowerShell/PowerShell/issues/3651
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多