码迷,mamicode.com
首页 > Web开发 > 详细

Async处理http请求

时间:2016-06-02 18:08:42      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

何谓Async?

请参考 http://www.cnblogs.com/jesse2013/p/async-and-await.html。

通过一下例子,看是怎样异步处理http请求的。

    public class ServerCmdHandle : HttpTaskAsyncHandler //继承异步处理方法
    {

    private async Task<string> DoAsync(HttpContext context, Object reqStr)
        {
            string recvInfo = System.Web.HttpUtility.UrlDecode(System.Text.Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(reqStr as string)));
            return await Task.Run(() =>
            {
                return Global.bus.ProcessBusiness(context, recvInfo);//实现异步处理的方法
            });
        }

        public override async System.Threading.Tasks.Task ProcessRequestAsync(HttpContext context)
        {
            try
            {
                string result = "";
                if (context.Request.RequestType.CompareTo("GET") == 0)
                {
                    result = await DoAsync(context, context.Request.QueryString["data"].ToString() as Object);
                }
                else if (context.Request.RequestType.CompareTo("POST") == 0)
                {
                    System.IO.Stream resStream = context.Request.GetBufferlessInputStream();
                    System.IO.StreamReader reader = new System.IO.StreamReader(resStream, Encoding.Default);
                    string resInfo = reader.ReadToEnd();
                    if (resInfo.Length > 0)
                    {
                        result = await DoAsync(context, resInfo as Object);//异步等待处理结果
                    }
                }
                else
                {
                    throw new Exception("user requset method error");
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write(result);
            }
            catch (Exception ex)
            {
                ServiceLogger.LOG_INFO("func=> ProcessRequestAsync:" + ex.Message, 0);
            }

        }


    }

 

Async处理http请求

标签:

原文地址:http://www.cnblogs.com/Yunshine-sina/p/5553659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!