/// <summary>
/// 异步回调测试
/// </summary>
public class AsnycCallBackController : ApiController
{
private AutoResetEvent autoResetEvent = new AutoResetEvent(false);
[HttpPost, ActionName("sendSms")]
public SmsInfo SendSms([FromBody] string smsContent)
{
SmsInfo info = new SmsInfo();
SmsCallBackUtil.SendSms(smsContent, (smsInfo) => {
info = smsInfo;
autoResetEvent.Set();
});
//阻止当前线程执行,只有当设置autoResetEvent.Set()后,才允许继续执行后面的代码逻辑(类似Thread.Sleep())
autoResetEvent.WaitOne();
return info;
}
}
/// <summary>
/// 短信回调工具类
/// </summary>
public class SmsCallBackUtil
{
/// <summary>
/// 发送短信
/// </summary>
/// <param name="smsContent">短信内容</param>
/// <param name="smsInfo">回调方法</param>
public static void SendSms(string smsContent, Action<SmsInfo> smsInfo)
{
SmsInfo info = new SmsInfo
{
content = smsContent,
senderName = "张发",
senderPhone = "13888888888",
receiverName = "李收",
receiverPhone = "13666666666"
};
//开启一个定时器模拟异步操作
Timer aTimer = new Timer();
aTimer.Elapsed += new ElapsedEventHandler((obj, eventArg) => {
aTimer.Enabled = false;
aTimer.Close();
aTimer = null;
smsInfo(info);
});
aTimer.Interval = 10000;//设置引发时间的时间间隔,定时10s
aTimer.AutoReset = false;//不允许重复执行
aTimer.Enabled = true;
aTimer.Start();
}
}
/// <summary>
/// 短信实体类
/// </summary>
public class SmsInfo
{
/// <summary> 短信发送内容 </summary>
public string content { get; set; }
/// <summary> 发送人姓名 </summary>
public string senderName { get; set; }
/// <summary> 发送人手机号码 </summary>
public string senderPhone { get; set; }
/// <summary> 接收人姓名 </summary>
public string receiverName { get; set; }
/// <summary> 接收人手机号码 </summary>
public string receiverPhone { get; set; }
}