异步处理程序

post方式请求一个异步处理程序获得json数据时,对于请求方来说,是需要等待整个handler执行完成的,而非仅仅开始一个异步的时间。

   /// <summary>
    /// AsyncHandler 的摘要说明
    ///  异步处理程序基类
    /// </summary>
    public abstract class AsyncHandlerBase : IHttpAsyncHandler
    {
        readonly Action<HttpContext> _processRequest;
        public AsyncHandlerBase()
        {
            _processRequest = ProcessRequest;
        }

        public abstract void ProcessRequest(HttpContext context);
        
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            context.Response.Write("异步开始了!");
            return _processRequest.BeginInvoke(context, cb, context);
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            _processRequest.EndInvoke(result);
            HttpContext context = result.AsyncState as HttpContext;
            context.Response.Write("到回调了!");
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    /// <summary>
    /// MyAsyncHandler 的摘要说明
    /// </summary>
    public class MyAsyncHandler : AsyncHandlerBase
    {
        public override void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.Write("\"mess\":\"即将休眠5秒\"");
            System.Threading.Thread.Sleep(5000);
            context.Response.Write("\"mess\":\"我以苏醒\"");
        }
    }
     public static void PostTest()
     {
         string reqUrl = "http://localhost:51233/MyAsyncHandler.ashx";
         string result = PostJsonDataToServer(reqUrl, "", HttpWebRequestMethod.GET, 6000);
         Console.WriteLine(result);
     }

 

posted @ 2018-06-30 14:48  王乐  阅读(166)  评论(0编辑  收藏  举报