简体   繁体   English

在 powershell 中使用任务 class

[英]Using the Task class in powershell

I'm trying to use the Task class in Powershell to run an operation asynchronously.我正在尝试使用 Powershell 中的任务 class 来异步运行操作。 But I'm getting the following exception:但我得到以下异常:

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

My code:我的代码:

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

It would take a lot of work to get PowerShell working with Task . 要让PowerShell使用Task需要做很多Task Task is too much of a low level construct for PowerShell to function with it directly. Task是一个低级别的构造,PowerShell可以直接使用它。

To perform PowerShell operations asynchronously use jobs . 要异步执行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