在powershell中使用Task类

mus*_*ium 7 powershell asynchronous task runspace

我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

我的代码:

$delegate = [System.Action]{ Write-Host "Test" }
[System.Threading.Tasks.Task]::Run($delegate)
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 4

让 PowerShell 与Task. Task对于 PowerShell 来说,它的底层结构太低,无法直接使用它。

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

  • 运行空间实现起来比较棘手,但可以[性能更高](http://learn-powershell.net/2012/05/13/using-background-runspaces-instead-of-psjobs-for-better-performance/)。 (3认同)