IHttpAsyncHandler, IRequiresSessionState, and IReadOnlySessionState Asynchronous Handler Issue

By Robbe Morris

IHttpAsyncHandler and IRequiresSessionState are still used with asynchronous http handlers. Remember to use the HttpContext passed into the http handler.



public class MyUploadClassHandler : IHttpAsyncHandler, IRequiresSessionState
  {
  
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
        {
             var upload = new MyUploadAsyncClass(cb, context, extraData);
             upload.Start();
            return upload;
        }

        public void EndProcessRequest(IAsyncResult result)
        {
         }

        public void ProcessRequest(HttpContext context)
        {
           
        }

        public bool IsReusable
        {
             get
             {
                 return false;
            }
        }

}



class MyUploadAsyncClass : IAsyncResult
{
        private bool _completed;
        private Object _state;
        private AsyncCallback _callback;
        private HttpContext _context;

        bool IAsyncResult.IsCompleted { get { return _completed; } }
       WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }
        Object IAsyncResult.AsyncState { get { return _state; } }
        bool IAsyncResult.CompletedSynchronously { get { return false; } }

        public MyUploadAsyncClass(AsyncCallback callback, HttpContext context, Object state)
        {
            _callback = callback;
            _context = context;
            _state = state;
            _completed = false;
        }

        public void Start()
        {
           ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncTask), null);
        }

        private void StartAsyncTask(Object workItemState)
        {
             string citation = string.Empty;

             try
            {
                 _context.Response.StatusCode = 200;

                 var uploads = (List<UploadItem>)_context.Session["UploadItems"];

                 if (uploads == null || uploads.Count < 1)
                 {
                     _context.Response.Write("|No uploads found in session.");
                     return;
                 }
                 
                 _context.Response.Write("do some stuff");

             }
             catch (Exception ex)
             {
               Utility.HandleError(ex);
            }
            finally
            {
                _completed = true;
                 _callback(this);
            }

        }
    }

IHttpAsyncHandler, IRequiresSessionState, and IReadOnlySessionState Asynchronous Handler Issue  (2201 Views)