IHttpAsyncHandler 的一個DEMO

    public class IHttpAsyncHandlerDEMO : IHttpHandler, IHttpAsyncHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            if (string.IsNullOrEmpty(context.Request.QueryString["IsAdd"]))
            {
                return new CustomIAsyncResult();
            }

            SqlConnection con = new SqlConnection("server=192.168.0.74;uid=sa;pwd=sa;database=Test;Asynchronous Processing=true");
            SqlCommand cmd = new SqlCommand("insert into tb2 values(1,1,1)", con);
            con.Open();
            return cmd.BeginExecuteNonQuery(cb, new CustomAsyncState { cmd = cmd, context = context });

        }

        public void EndProcessRequest(IAsyncResult result)
        {
            if (result is CustomIAsyncResult)
            {
                HttpContext.Current.Response.Write("無效參數!");
            }
            else
            {
                //result.AsyncState
                CustomAsyncState state = result.AsyncState as CustomAsyncState;
                if (state != null)
                {
                    int count = 0;
                    if (state.cmd != null)
                    {
                        count = state.cmd.EndExecuteNonQuery(result);
                        if (state.cmd.Connection != null)
                        {
                            state.cmd.Connection.Close();
                            state.cmd.Connection.Dispose();
                        }
                    }

                    if (state.context != null)
                    {
                        state.context.Response.Write(string.Format("增加{0}條記錄", count));
                    }
                }
            }
        }
    }


 

    internal class CustomAsyncState
    {
        internal HttpContext context { set; get; }
        internal SqlCommand cmd { set; get; }
    }


 

    internal class CustomIAsyncResult : IAsyncResult
    {

        public object AsyncState
        {
            get { return ""; }
        }

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

        public bool CompletedSynchronously
        {
            get { return true; }
        }

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章