考虑以下代码(这非常简单,但仅用于测试目的):
class Program
{
static void Main(string[] args)
{
Test t1 = new Test();
object output = t1.Run();
Test t2 = new Test();
t2.RunAsync();
t2.EndAsync();
}
}
class Test
{
RunspacePool rsPool;
PowerShell p;
IAsyncResult asyncResult;
Object output;
public Test()
{
rsPool = RunspaceFactory.CreateRunspacePool(1, 10);
rsPool.Open();
p = PowerShell.Create();
p.RunspacePool = rsPool;
p.AddCommand("Get-Service");
}
public object Run()
{
output = null;
asyncResult = p.BeginInvoke();
output = p.EndInvoke(asyncResult);
return output;
}
public void RunAsync()
{
output = null;
p.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(p_InvocationStateChanged);
asyncResult = p.BeginInvoke();
}
public object EndAsync()
{
// Dirty, but for test purpose only
while (output == null)
System.Threading.Thread.Sleep(100);
return output;
}
void p_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e)
{
if (e.InvocationStateInfo.State == PSInvocationState.Completed)
output = p.EndInvoke(asyncResult);
}
}
测试t1
正确结束,output
包含Get-Service CommandLet的结果。
调用达到状态已完成后,测试t2
仍然卡在output = p.EndInvoke(asyncResult);
上。