C# 异步回调

    /// <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; }

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值