9

I’m trying to use the Task class in Powershell to run an operation asynchronously. 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)
musium
  • 2,942
  • 3
  • 34
  • 67

2 Answers2

4

It would take a lot of work to get PowerShell working with Task. Task is too much of a low level construct for PowerShell to function with it directly.

To perform PowerShell operations asynchronously use jobs.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • 3
    Runspaces are more tricky to implement but can be [more performant](http://learn-powershell.net/2012/05/13/using-background-runspaces-instead-of-psjobs-for-better-performance/). – user2871239 Dec 02 '14 at 19:23
  • Unfortunately it looks like runspaces are broken, as each invoke runs sequentially instead of in parallel. If someone can convert a ScriptBlock to a lamda, I would much prefer using Tasks. https://github.com/PowerShell/PowerShell/issues/3651 – Brain2000 Dec 09 '18 at 18:44
1
Install-Module PSRunspacedDelegate -Scope CurrentUser

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