首頁  >  文章  >  後端開發  >  C# HttpHandler 非同步監聽請求的程式碼詳解

C# HttpHandler 非同步監聽請求的程式碼詳解

黄舟
黄舟原創
2017-03-03 11:28:411978瀏覽

在高並發下的伺服器端編程,當遇到效能瓶頸時候,往往是同步帶來的。監聽HTTP請求的時候,非同步是必須的。

非同步監聽HTTP請求的基底類別:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;


namespace MyHandler
{
    public abstract class HttpAsyncHandler : IHttpAsyncHandler, IAsyncResult
    {
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            _callback = cb;
            _context = context;
            _completed = false;
            _state = this;


            ThreadPool.QueueUserWorkItem(new WaitCallback(DoProcess), this);
            return this;
        }


        public void EndProcessRequest(IAsyncResult result)
        {


        }


        public bool IsReusable
        {
            get { return false; }
        }


        public abstract void BeginProcess(HttpContext context);


        public void EndProcess()
        {
            //防止多次进行多次EndProcess


            if (!_completed)
            {
                try
                {
                    _completed = true;
                    if (_callback != null)
                    {
                        _callback(this);
                    }
                }
                catch (Exception) { }
            }
        }


        private static void DoProcess(object state)
        {
            HttpAsyncHandler handler = (HttpAsyncHandler)state;
            handler.BeginProcess(handler._context);
        }


        public void ProcessRequest(HttpContext context)
        {
            throw new NotImplementedException();
        }


        private bool _completed;
        private Object _state;
        private AsyncCallback _callback;
        private HttpContext _context;


        public object AsyncState
        {
            get { return _state; }
        }


        public WaitHandle AsyncWaitHandle
        {
            get { throw new NotImplementedException(); }
        }


        public bool CompletedSynchronously
        {
            get { return false; }
        }


        public bool IsCompleted
        {
            get { return _completed; }
        }
    }
}

新增TestHandler.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace MyHandler
{
    public class TestHandler : HttpAsyncHandler
    {
        public override void BeginProcess(System.Web.HttpContext context)
        {
            try
            {
                StreamReader sr = new StreamReader(context.Request.InputStream);


                string reqStr = sr.ReadToEnd();
                context.Response.Write("get your input : " + reqStr + " at " + DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                context.Response.Write("exception eccurs ex info : " + ex.Message);
            }
            finally
            {
                EndProcess();////最后别忘了end
            }


        }
    }
}

在網站引入MyHandler.dll,並依照下列修改WebConfig:

<?xml version="1.0" encoding="utf-8"?>


<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
    <httpRuntime requestValidationMode="2.0"/>
    <customErrors mode="Off"/>
    <httpHandlers>
      <add verb="*" path="Test.aspx" type="MyHandler.TestHandler, MyHandler"/>
    </httpHandlers>
  </system.web>


</configuration>

 以上就是C#   HttpHandler  非同步監聽請求的程式碼詳解的內容,更多相關內容請關注PHP中文網(www.php.cn)!




#
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn