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 List();
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(List records);
// the actual method that does the work
public void AsyncProcess(List 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
<div class="progress progress-striped">
<div class="bar" style="width: 0%;"></div>
</div>
<input type="button" class="btn btn-primary" value="Start!" onclick="start();"/>
<script type="text/javascript">
// function to launch the mail process
function start() {
$.post('/Admin/Async', function (data) {
if (data.Exception) {
alert(data.Exception);
return;
} else {
alert(data.Result);
updateStatus();
}
});
}
// update the progress bar
function updateStatus() {
$.ajax({
url: "/Admin/AsyncStatus",
type: "GET",
cache: false,
dataType: "json",
success: function (data) {
var percentComplete = parseInt(data.PercentComplete);
if (percentComplete == null || percentComplete == 100) {
$(".progress").removeClass("active"); // we're done!
$(".progress .bar").css("width", "100%");
} else { // update the progress bar
$(".progress").addClass("active");
$(".progress .bar").css("width", percentComplete + "%");
setTimeout(updateStatus, 1000); // call self to refresh
}
}
});
}
</script>
Comentarios
Publicar un comentario