C# 在返回之前等待调用操作
在我的项目中,我使用WebApi2做一些事情并返回一个Id: 控制器C# 在返回之前等待调用操作,c#,asp.net,.net,asp.net-web-api,C#,Asp.net,.net,Asp.net Web Api,在我的项目中,我使用WebApi2做一些事情并返回一个Id: 控制器 [HttpGet, Route("call")] public IHttpActionResult MakeCall(string poste, string number) { string phoneFrPattern = "^0[1-9][0-9]{8}$"; Match m = Regex.Match(number, phoneFrPattern);
[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();
}
}
上面的代码运行得很好,除了这个动作不要等待我的动作(callId)=>。。。要至少调用一次,我需要从事件返回一个Id
MakeCall方法:
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);
}
}
public void MakeCall(字符串标识符、字符串电话号码、调用操作)
{
if(null==运算符工厂)
抛出新异常(“OperatorManager.OperatorFactory为空”);
IOperator@operator=\u operators.FirstOrDefault(o=>o.Identifier==Identifier);
if(空!=@运算符)
{
@操作符OnDialing+=(e)=>OnDialing(e.CallId);
@operator.IsCalling=true;
@接线员呼叫(电话号码);
}
其他的
{
@operator=OperatorFactory.Create(标识符);
@操作符OnDialing+=(e)=>OnDialing(e.CallId);
@operator.IsCalling=true;
@操作符Connect();
@接线员呼叫(电话号码);
}
}
您可以使用任务等待,就像这样
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);
var t=new TaskCompletionSource();
_operatorManager.MakeCall(poste,“0”+号码,(callId)=>
{
t、 SetResult(callId);
});
t、 Task.Wait();
_response.Clear();
_添加(“callId”,t.Task.Result);
返回Ok(_响应);
TaskCompletionSource提供了各种处理方法。其他选项是从MakeCall方法返回任务,或者在MakeCall方法内执行相同的操作并同步返回callId 谁引发了OnDialing?OnDialing是由我的合作伙伴提供的外部关闭DLL引发的。我的完整源代码可以在网站上找到,谢谢你的回答。我想我会做一个临时任务,在行动中我会等待它。你觉得呢?这个代码只在一段时间内有效。如果我回忆起这个方法,请求将处于挂起状态。