2013-02-25 19 views
5

Tôi đang cố gắng sử dụng lớp Task trong Powershell để chạy một hoạt động không đồng bộ. Nhưng tôi nhận được ngoại lệ sau đây:Sử dụng lớp Task trong powershell

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 

Mã của tôi:

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

Trả lời

3

Nó sẽ mất rất nhiều công việc để có được PowerShell làm việc với Task. Task là quá nhiều cấu trúc cấp thấp để PowerShell hoạt động trực tiếp với nó.

Để thực hiện các thao tác PowerShell sử dụng không đồng bộ jobs.

+3

Không gian triển khai khó thực hiện hơn nhưng có thể [hiệu quả hơn] (http://learn-powershell.net/2012/05/13/using-background-runspaces-instead-of-psjobs-for-better-performance /). – user2871239

Các vấn đề liên quan