• Task Asnyc 异常问题


    /// <summary>
            /// async 异常捕获问题
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            static async Task<string> TestException(string context) {
                return string.Format("【{0}】 长度:【{1}】",context,context.Length);
            }
    
            /// <summary>
            /// 该方法无法获取异常
            /// </summary>
            static void Test1()
            {
                try
                {
                     //产生异常  无法捕获异常
                     TestException(null).ContinueWith(r =>{
                         Console.WriteLine(r.Result);
                     });
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
    
            /// <summary>
            /// 不能报异常(async与await一起使用)
            /// </summary>
            /// <returns></returns>
            static async Task Test2()
            {
                string result = await TestException(null);
                string test = result;
            }


     Http async / await 方式请求实例:

        public static async Task<string> HttpGet(string Url)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
    
                using (var response =await request.GetResponseAsync())
                {
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                    string retString = myStreamReader.ReadToEnd();
                    return retString;
                }
            }
    
            public static async Task<string> HttpPostAsync(string url, string postData)
            {
                try
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    request.ContentLength = byteArray.Length;
                    using (Stream myRequestStream = await request.GetRequestStreamAsync())
                    {
                        myRequestStream.Write(byteArray, 0, byteArray.Length);
                        WebResponse response = request.GetResponse();
                        StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                        return myStreamReader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info(ex);
                    return string.Empty;
                }
               
            }
            
            public static async Task<string> HttpPostAsync(string url, Dictionary<string,string> paramList)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in paramList)
                    {
                        sb.Append(item.Key + "=" + item.Value + "&");
                    }
                    string paramData = sb.ToString().Trim('&');
                    byte[] data = System.Text.Encoding.UTF8.GetBytes(paramData);
                    request.Method = "post";
                    //这句不能少  不难post请求 得不到对应的响应结果
                    request.ContentType = "application/x-www-form-urlencoded";
                    using (Stream myRequestStream = await request.GetRequestStreamAsync())
                    {
                        myRequestStream.Write(data, 0, data.Length);
                        WebResponse response = request.GetResponse();
                        StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                        return myStreamReader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info(ex);
                    return string.Empty;
                }
    
            }
        /// <summary>
            /// PPTV点卡充值
            /// </summary>
            /// <param name="mobie">手机号</param>
            /// <param name="cardnumber">点卡卡密</param>
            /// <returns></returns>
            public async Task<string> ExchangePPTVCard(string mobie, string cardnumber)
            {
                string agent = "lemon_act";
                string agentkey = "HF0abDEc";
                string username = mobie;
                //aesyhhxw72453525  月卡
                //hnscpyau66772763  半年卡
                //mwusrbdu45743377  年卡
                //string cardnumber = "hnscpyau66772763";
                string urlEncodeUsername = StringHelper.UrlEncode(username);
                string sign = StringHelper.MD5(StringHelper.UrlEncode(string.Format("{0}&{1}&{2}",username,cardnumber,agentkey)));
                Dictionary<string, string> paramList = new Dictionary<string, string>();
                paramList.Add("username", urlEncodeUsername);
                paramList.Add("cardnumber", cardnumber);
                paramList.Add("agent", agent);
                paramList.Add("sign", sign);
                string url = "https://api.vip.pptv.com/ppcard/exchange";
                string result = await HttpHelper.HttpPostAsync(url, paramList);
                UserPPTVCardExchangeResultModel exchangeResult = JsonConvert.DeserializeObject<UserPPTVCardExchangeResultModel>(result);
                return result;
            }
    /// <summary>
            /// 充值点卡
            /// </summary>
            /// <param name="mobile">手机号(手机号必须注册)</param>
            /// <param name="cardnumber">点卡卡密</param>
            /// <returns></returns>
             [HttpGet, Route("ExchangeCard")]
            public async Task<Result<bool>> ExchangeCard(string mobile,string cardnumber)
            {
                Result<bool> result = new Result<bool>();
                try
                {
                    string secretKey = Request.Headers.GetValues("SecretKey").FirstOrDefault();
                    ChannelsService channelservice = new ChannelsService();
                    int channelId = channelservice.GetChannerIdBySecretKey(secretKey);
    
                    UsersService userService = new UsersService();
                    //1.判断手机是否存在
                    bool isExist = userService.IsRegisterPPTVByMobile(mobile, channelId);
                    result.ReturnCode = StateCode.Success;
                    if (!isExist)
                    {
                        Logger.Warn(string.Format("【0】手机号尚未注册",mobile));
                        result.Data = false;
                        result.ReturnMsg = "该手机尚未注册";
                        return result;
                    }
                    //2.判断该点卡是否可以使用
                    bool isEnable = await PPTVCardInfo(mobile,cardnumber);
                    if (!isEnable)
                    {
                        Logger.Warn(string.Format("【0】点卡卡密已经被使用", cardnumber));
                        result.Data = false;
                        result.ReturnMsg = "该点卡卡密已经被使用";
                        return result;
                    }
                    //3.充值PPTV点卡
                    bool isChange = await ExchangePPTVCard(mobile, cardnumber);
                    if (!isChange)
                    {
                        result.Data = false;
                        result.ReturnMsg = "该点卡卡密已经被使用";
                        return result;
                    }
                    result.Data = userService.ExchangePPTVCard(cardnumber);
                    if (result.Data)
                    {
                        result.ReturnMsg = "充值点卡成功";
                    }
                    else
                    {
                        result.ReturnMsg = "充值点卡失败";
                    }
                }
                catch (Exception ex)
                {
                    result.ReturnMsg = "服务器内部发生异常";
                    Logger.Error("UsersController[ExchangeCard]", ex);
                }
                return result;
            }

     使用Task.Run(()=>{})方式执行

     /// <summary>
                /// 更新订单状态
                /// </summary>
                /// <param name="consumptionId">订单ID</param>
                /// <param name="totalFee">总费用</param>
                /// <param name="status">状态</param>
                /// <returns></returns>
                public async Task<bool> CheckUserConsumptionStatus(Guid consumptionId, string buyerEmail, decimal totalFee, int status)
                {
    
                    return await Task.Run(() => {
                        //TODO
                         return true;
       
                    });
                    
                }
  • 相关阅读:
    Windows 7/8 删除IE临时文件,包括Cookie的批处理
    SQL Server 2005/2008/2008R2/2012 删除登录名的步骤
    NetAdvangate Infragisticss 控件在工程移动到别的机器上,引用失效问题
    如果一个主板有多个BIOS更新包,则只需要更新最新的包即可。
    Intel存储技术软件的兼容性问题,造成磁盘IO不稳,卡死系统
    汤姆大叔JavaCript系列4阅读笔记
    IDL(接口描述语言)
    document.defaultView.getComputedStyle() 的使用
    汤姆大叔JavaCript系列1阅读笔记
    汤姆大叔JavaCript系列10阅读笔记
  • 原文地址:https://www.cnblogs.com/zoro-zero/p/5455807.html
Copyright © 2020-2023  润新知