Saturday, 14 June 2014

AsyncController in MVC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : AsyncController
    {
        //
        // GET: /Home/
        private readonly object _lock = new object();
        public void IndexAsync()
        {
            AsyncManager.OutstandingOperations.Increment();
            Operation1();
            Operation2();
        }
        public ActionResult IndexCompleted(string Operation1, string Operation2)
        {
            ViewData["Operation1"] = Operation1;
            ViewData["Operation2"] = Operation2;
            return View();
        }
        void Operation1()
        {
            lock (_lock)
            {
                AsyncManager.Parameters["Operation1"] = "Result1";
            }
            AsyncManager.OutstandingOperations.Decrement();
        }
        void Operation2()
        {
            lock (_lock)
            {
                AsyncManager.Parameters["Operation2"] = "Result2";
            }
            AsyncManager.OutstandingOperations.Decrement();
        }
    }
}
PAGE
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<body>
<div>
<p>@ViewData["Operation1"] </p>
<p>@ViewData["Operation2"]</p>
</div>
</body>

No comments:

Post a Comment