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=xxx;uid=xxx;pwd=xxx;database=Test;Asynchronous Processing=true");
SqlCommand cmd = new SqlCommand("insert into xxx 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; }
}
}
IHttpAsyncHandlerDEMO.ashx -> 无效参数!
IHttpAsyncHandlerDEMO.ashx?IsAdd -> 无效参数!
IHttpAsyncHandlerDEMO.ashx?IsAdd=2 -> 增加x条记录