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

來源:互聯網
上載者:User
在高並發下的伺服器端編程,當遇到效能瓶頸時候,往往是同步帶來的。監聽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 非同步監聽請求的代碼詳解的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.