如何使用AsyncCallback获取方法结果?

时间:2013-08-15 14:51:24

标签: c#

我希望你能帮我解决以下问题:

我有一个WebService方法,它应该返回一个CompensationPlanReturnReturn对象数组。 该方法如下所示:

//This is the object I need to instanciate  because it contains the method I wanna call
CompensationPlan_Out_SyncService test = new CompensationPlan_Out_SyncService();
//This is the method that is supposed to return me an array of CompensationPlanReturnReturn objects
//The data.ToArray() is the parameter the method need, then I pass the method that I wanna run when the method finishes and I dont know what to pass as the final parameter
test.BeginCompensationPlan_Out_Sync(data.ToArray(), new AsyncCallback(complete), null)

//The method description is:
public System.IAsyncResult BeginCompensationPlan_Out_Sync(CompensationPlanDataCompensationPlan[] CompensationPlanRequest, System.AsyncCallback callback, object asyncState)

//On this method I'd like to access to the resuls (the array of CompensationPlanReturnReturn) but I dont know how
private void complete(IAsyncResult result)
    {            
        lblStatus.Text = "Complete";
    }

3 个答案:

答案 0 :(得分:4)

您需要调用test.EndCompensationPlan_Out_Sync(result),它将返回异步操作的结果,或者在发生错误时抛出异常。

答案 1 :(得分:2)

异步方法分为两个子方法 - BeginEnd

您需要调用EndCompensationPlan_Out_Sync来获取方法返回的实际结果 -

private void complete(IAsyncResult result)
{            
    var actualResult = test.EndCompensationPlan_Out_Sync(result);
    lblStatus.Text = "Complete";
}

答案 2 :(得分:0)

尝试使用AsyncState-Property并将其转换为给定的Type。

像这样:

cSACommand = (SACommand)Result.AsyncState;