C#中的回调函数

时间:2013-02-26 09:45:56

标签: c# asynchronous methods callback

我必须使用回调(asynchron)调用api(SOAP),result..etc。 我必须使用的方法:

public IAsyncResult BeginInsertIncident(
    string userName, string password, string MsgId, string ThirdPartyRef,
    string Type, string EmployeeId, string ShortDescription, string Details,
    string Category, string Service, string OwnerGrp, string OwnerRep,
    string SecondLevelGrp, string SecondLevelRep, string ThirdLevelGrp,
    string ThirdLevelRep, string Impact, string Urgency, string Priority,
    string Source, string Status, string State, string Solution,
    string ResolvedDate, string Cause, string Approved, AsyncCallback callback,
    object asyncState);

EndInsertIncident(IAsyncResult asyncResult, out string msg);

EndInsertIncident关闭Ticketsystem中的请求,并在故障单正确完成后给出结果。

现状:

server3.ILTISAPI api = new servert3.ILTISAPI();
api.BeginInsertIncident(username, "", msg_id, "", "", windows_user,
    "BISS - Software Deployment", "", "", "NOT DETERMINED", "", "", "", "", "",
    "", "5 - BAU", "3 - BAU", "", "Interface", "", "", "", "", "", "", null,
    null);

那么,现在,我如何实现Callback-Function? api“InsertIncidentCompleted”的状态ist已经为null,因为我认为我没有调用EndInsertIncident。

我是C#的新手,需要一些帮助。

1 个答案:

答案 0 :(得分:0)

AsyncCallback是一个委托,它返回void并接受一个IAsyncResult类型的参数。

因此,使用此签名创建一个方法,并将其作为倒数第二个参数传递:

private void InsertIncidentCallback(IAsyncResult result)
{
    // do something and then:
    string message;
    api.EndInsertIncident(result, out message);
}

像这样传递:

api.BeginInsertIncident(username, "", msg_id, "", "", windows_user,
    "BISS - Software Deployment", "", "", "NOT DETERMINED", "", "", "", "", "",
    "", "5 - BAU", "3 - BAU", "", "Interface", "", "", "", "", "", "",
    InsertIncidentCallback, null);

如果你不能让api成为你班级的成员变量,并希望将其传递给你的回调,你必须做这样的事情:

private void InsertIncidentCallback(server3.ILTISAPI api, IAsyncResult result)
{
    // do something and then:
    string message;
    api.EndInsertIncident(result, out message);
}

为了能够将其作为回调传递,您必须使用委托:

api.BeginInsertIncident(..., r => InsertIncidentCallback(api, r), null);