簡體   English   中英

在 powershell 中使用任務 class

[英]Using the Task class in powershell

我正在嘗試使用 Powershell 中的任務 class 來異步運行操作。 但我得到以下異常:

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使用Task需要做很多Task Task是一個低級別的構造,PowerShell可以直接使用它。

要異步執行PowerShell操作,請使用作業

Install-Module PSRunspacedDelegate -Scope CurrentUser

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM