Peter
Peter

Reputation: 75

Waiting for action to be invoke before returning

In my project, I use WebApi2 to do some stuff and returning an Id :

Controller.cs

    [HttpGet, Route("call")]
    public IHttpActionResult MakeCall(string poste, string number)
    {
        string phoneFrPattern = "^0[1-9][0-9]{8}$";
        Match m = Regex.Match(number, phoneFrPattern);
        if (m.Success && _isNumeric(poste))
        {
            _operatorManager.MakeCall(poste, "0" + number, (callId) =>
            {
                _response.Clear();
                _response.Add("callId", callId);
            });
            return Ok(_response);
        }
        else
        {
            return InternalServerError();
        }
    }

This above code works very well except this action don't wait my Action (callId) =>... to be Invoke at least once and I need to return an Id from an event.

MakeCall method :

    public void MakeCall(string identifier, string phoneNumber, Action<string> onDialing)
    {
        if (null == OperatorFactory)
            throw new Exception("OperatorManager.OperatorFactory is null");

        IOperator @operator = _operators.FirstOrDefault(o => o.Identifier == identifier);
        if (null != @operator)
        {
            @operator.OnDialing += (e) => onDialing(e.CallId);
            @operator.IsCalling = true;
            @operator.Call(phoneNumber);
        }
        else
        {
            @operator = OperatorFactory.Create(identifier);
            @operator.OnDialing += (e) => onDialing(e.CallId);
            @operator.IsCalling = true;
            @operator.Connect();
            @operator.Call(phoneNumber);
        }
    }

Upvotes: 1

Views: 4127

Answers (1)

Irdis
Irdis

Reputation: 986

You can wait it using Task, like that.

        var t = new TaskCompletionSource<int>();
        _operatorManager.MakeCall(poste, "0" + number, (callId) =>
        {
            t.SetResult(callId);
        });
        t.Task.Wait();
        _response.Clear();
        _response.Add("callId", t.Task.Result);
        return Ok(_response);

TaskCompletionSource provides various ways to handle this. Other options would be to return a task from MakeCall method, or do the same trick inside the MakeCall method and synchronously return callId.

Upvotes: 3

Related Questions