包装方法以等待回调

时间:2017-07-03 12:17:09

标签: c# delegates async-await

我有一个客户端代码(ViewModeL)正在调用ConnectedThingService来调用CoapService来更新"事情"的模式。 CoapService上的更新方法返回一个任务,并具有成功和错误响应的参数。

Task<Task> SetModeFrom(DeviceModel Device, CoAPResponseReceivedHandler responseHandler, CoAPErrorHandler errorHandler);``` 

CoAPResponseRecivedHandler和CoAPErrorHandler是委托。

以下是调用CoapService的代码:

public async Task<ApiResponse> UpdateModeAsync(int mode)
{
    ApiResponse result = new ApiResponse();
    await _coapService.SetControlModeFromCombo(device, (updateResp) =>
    {
        if (updateResp.Code.Value != CoAPMessageCode.CONTENT)
        {
            result.IsSuccessful = false;
            result.ErrorMessages.Add("Failed setting mode");
        }
        else
        {
            var coapResponse = 
JsonConvert.DeserializeObject<ControlModel>(updateResp.GetPayload());
            result.IsSuccessful = true;
            Mode = mode;
        }
    }, (e, associatedMsg) =>
    {
        result.IsSuccessful = false;
        result.ErrorMessages.Add("Failed setting mode");
    }); 
    return result;

问题是在任一代表触发之前调用正在返回,因此我总是在ApiResponse中返回false(默认值)。有没有办法进行此调用并等待2个代理中的任何一个在返回客户端之前被调用,并且以不阻塞的方式执行此操作?是否有可能超时,以便如果两个代表都没有在超时时间后触发,它会返回false?

编辑:我继承了这段代码。最低级代码来自CoAPSharp.com。以下是SetControlModeFromCombo的代码:

public async Task<Task> SetControlModeFromCombo(DeviceModel Device, 
CoAPResponseReceivedHandler responseHandler, CoAPErrorHandler 
errorHandler)
{
    ushort msgID = Convert.ToUInt16(new Random().Next(1000, 9999));
    var task = new TaskCompletionSource<DeviceModel>();
    if (!string.IsNullOrWhiteSpace(Device.CODE))
    {
        var controlSettings = new ControlModel()
        {
            Mode = Device.ComboSettings.Mode,
        };
        await _coap.MakeRequest(Device.CODE, JsonConvert.SerializeObject(controlSettings.ControlMode()), Device.IPADDRESS, ControlModel.Endpoint, CoAPMessageType.CON, CoAPMessageCode.PUT, msgID, (CoAPResponse response) =>
        {
            responseHandler(response);
            task.SetResult(Device);
        }, (Exception e, AbstractCoAPMessage associatedMsg) =>
        {
            errorHandler(e, associatedMsg);
        });
    }
    else
    {
        ThrowMissingCodeError(task);
    }
    return task.Task;
}

这是MakeRequest方法:

public async Task MakeRequest(string token, string outboundIP, string uri, byte type, byte code, ushort id, CoAPResponseReceivedHandler responseHandler, CoAPErrorHandler errorHandler)
{
    try
    {
        _coapClient = new CoAPClientChannel();
        await _coapClient.Initialize(outboundIP, _outboundPort);
        _coapClient.CoAPResponseReceived += responseHandler;
        _coapClient.CoAPError += errorHandler;
        await _coapClient.Send(AssembleRequest(type, code, id, outboundIP, uri, token), outboundIP);
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
    }

}

0 个答案:

没有答案