C#中的回调函数

本文关键字:函数 回调 | 更新日期: 2023-09-27 18:01:15

我必须用回调(异步(调用api(SOAP(,结果。。等我必须使用的方法:

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关闭Tickets系统中的请求,并在票证正确完成的情况下给出结果。

现状:

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

那么,现在,我如何实现回调函数呢?api"InsertIncidentCompleted"的状态已经为null,因为我认为我没有调用EndInsertIncident。

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

C#中的回调函数

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