:::: MENU ::::

Tuesday, October 14, 2014

 
C# 

        public ActionResult Async()
        {
            return View();
        }

        // Submit this page to begin processing
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Async(FormCollection collection)
        {
            try
            {
                // some test data
                var records = new ArrayList();
                for (var i = 0; i < 10; i++)
                    records.Add(i);

                // async storage (must be at app level?)
                HttpContext.Application["RecordsTotal"] = records.Count;
                HttpContext.Application["RecordsProcessed"] = 0;

                var caller = new AsyncProcessCaller(AsyncProcess);
                caller.BeginInvoke(records, null, null);

                return Json(new { Result = "Started..." }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Exception = ex.ToString() }, JsonRequestBehavior.AllowGet);
            }
        }

        // provide a signature for executing asynchronusly
        public delegate void AsyncProcessCaller(ArrayList records);

        // the actual method that does the work
        public void AsyncProcess(ArrayList records)
        {
            // do stuff with the records
            foreach (var record in records)
            {
                System.Threading.Thread.Sleep(1000); // pretend we did labor intesive work
                HttpContext.Application["RecordsProcessed"] = (int)HttpContext.Application["RecordsProcessed"] + 1;
            }
        }

        // a method that returns the status, call this with javascript to update your status bar
        public JsonResult AsyncStatus()
        {
            var total = (int)HttpContext.Application["RecordsTotal"];
            var processed = (int)HttpContext.Application["RecordsProcessed"];
            var percent = Math.Round(((decimal)processed / (decimal)total) * 100, 0);

            return Json(new { PercentComplete = percent }, JsonRequestBehavior.AllowGet);
        }
 
 
HTML

 

       

            0%