完成异步操作捕获事件

时间:2015-10-23 13:41:01

标签: c# powershell asynchronous

考虑以下代码(这非常简单,但仅用于测试目的):

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);上。

我严格不明白为什么。 有人可以帮忙吗?

0 个答案:

没有答案