在 PowerShell 中异步调用 System.Action 实例

问题描述 投票:0回答:3

背景

首先我创建一个

System.Action
实例:

PS C:\Users\KnutKristian> $a = [Action]{}

看看成员们:

PS C:\Users\KnutKristian> $a | gm

   TypeName: System.Action

Name              MemberType Definition                                        
----              ---------- ----------                                        
BeginInvoke       Method     System.IAsyncResult BeginInvoke(System.AsyncCal...
Clone             Method     System.Object Clone(), System.Object ICloneable...
DynamicInvoke     Method     System.Object DynamicInvoke(Params System.Objec...
EndInvoke         Method     void EndInvoke(System.IAsyncResult result)        
Equals            Method     bool Equals(System.Object obj)                    
GetHashCode       Method     int GetHashCode()                                 
GetInvocationList Method     System.Delegate[] GetInvocationList()             
GetObjectData     Method     void GetObjectData(System.Runtime.Serialization...
GetType           Method     type GetType()                                    
Invoke            Method     void Invoke()                                     
ToString          Method     string ToString()                                 
Method            Property   System.Reflection.MethodInfo Method {get;}        
Target            Property   System.Object Target {get;}

BeginInvoke
签名:

PS C:\Users\KnutKristian> $a.BeginInvoke.OverloadDefinitions
System.IAsyncResult BeginInvoke(System.AsyncCallback callback, System.Object ob
ject)

当我尝试开始调用时,出现此错误:

PS C:\Users\KnutKristian> $a.BeginInvoke($null, $null)
Exception calling "BeginInvoke" with "2" argument(s): "The object must be a run
time Reflection object."
At line:1 char:1
+ $a.BeginInvoke($null, $null)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

指定内容没有帮助:

PS C:\Users\…> $a.BeginInvoke([AsyncCallback]{param([IAsyncResult] $a)}, '')
Exception calling "BeginInvoke" with "2" argument(s): "The object must be a run
time Reflection object."
At line:1 char:1
+ $a.BeginInvoke([AsyncCallback]{param([IAsyncResult] $a)}, '')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

一些异常信息:

PS C:\Users\KnutKristian> $Error[0].Exception.InnerException | gm


   TypeName: System.ArgumentException

Name             MemberType Definition                                         
----             ---------- ----------                                         
Equals           Method     bool Equals(System.Object obj), bool _Exception....
GetBaseException Method     System.Exception GetBaseException(), System.Exce...
GetHashCode      Method     int GetHashCode(), int _Exception.GetHashCode()    
GetObjectData    Method     void GetObjectData(System.Runtime.Serialization....
GetType          Method     type GetType(), type _Exception.GetType()          
ToString         Method     string ToString(), string _Exception.ToString()    
Data             Property   System.Collections.IDictionary Data {get;}         
HelpLink         Property   string HelpLink {get;set;}                         
HResult          Property   int HResult {get;}                                 
InnerException   Property   System.Exception InnerException {get;}             
Message          Property   string Message {get;}                              
ParamName        Property   string ParamName {get;}                            
Source           Property   string Source {get;set;}                           
StackTrace       Property   string StackTrace {get;}                           
TargetSite       Property   System.Reflection.MethodBase TargetSite {get;}


PS C:\Users\KnutKristian> $Error[0].Exception.InnerException |
    fl Message, ParamName, InnerException -Force


Message        : The object must be a runtime Reflection object.
ParamName      : 
InnerException : 

问题

  1. 消息内容是什么

    该对象必须是运行时反射对象。

    在这种情况下意味着什么?据我所知,这里只有 .NET 对象。也许抱怨一些 PowerShell 具体细节?

  2. 如何成功运行

    BeginInvoke
    方法?

powershell asynchronous lambda begininvoke
3个回答
1
投票

尝试下面的代码。

[Action]{}|%{$_.BeginInvoke($null, $null)}


IsCompleted            : True
AsyncDelegate          : System.Action
AsyncState             :
CompletedSynchronously : False
EndInvokeCalled        : False
AsyncWaitHandle        : System.Threading.ManualResetEvent
NextSink               :

请看下面的文章来了解RunTimeType http://msdn.microsoft.com/en-us/library/ms172329.aspx


0
投票

要异步运行,您可以尝试

jobs
(多进程方式,效率不高),或者您可以尝试创建
RunspacePool
,如这篇文章所示。


0
投票

你可以试试这个。当你启动代码时,你可以看到你可以在Powershell的控制台中输入,尽管有Start-Sleep函数,所以这是一个异步函数。如果等待 5 秒钟,然后键入 Enter,您将获得 BeginInvoke 函数的结果。如果您不等待 5 秒,然后输入 Enter,则必须等待 BeginInvoke 函数结束,所以需要 5 秒。

using assembly System;

$psInstance = [System.Management.Automation.PowerShell]::Create().AddScript({ $getprocess = Get-Process; Start-Sleep -Seconds 5; Write-Output $getprocess; });
$asyncResult = $psInstance.BeginInvoke();
Read-Host;

$psInstance.EndInvoke($asyncResult);
Read-Host;
© www.soinside.com 2019 - 2024. All rights reserved.