2013-02-25 85 views
5

我試圖使用Powershell中的Task類異步運行一個操作。 但我發現了以下異常:在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) 

回答

3

這將需要大量的工作來獲取PowerShell和Task工作。 Task是PowerShell直接運行的低級構造。

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

+3

運行空間的實現比較棘手,但可以[更高性能](http://learn-powershell.net/2012/05/13/using-background-runspaces-instead-of-psjobs-for-better-performance /)。 – user2871239 2014-12-02 19:23:45