HOW TO USE SYSTEM.THREADING.TASKS IN C# MVC.

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C#  Mvc 
 914  View(s)
Ratings:
Rate this:
Can anyone please help me how to solve this problem.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: How to Use System.Threading.Tasks in c# MVC.

      The Task class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the Task.Run or TaskFactory.StartNew method is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the Task.Start method to schedule the task for execution at a later time.

     

    <div>

    sample execution time

    <br />

    Data1:@ViewBag.GetData1

    <br />

    Data2:@ViewBag.GetData1

    <br />

    Data3:@ViewBag.GetData1

    <br />

    Data4:@ViewBag.GetData1

    <br />

    execution time:@ViewBag.btime

    <br />

    After Useing tasking execution time

    <br />

    Data1: @ViewBag.Data1

    <br />

    Data2: @ViewBag.Data1

    <br />

    Data3: @ViewBag.Data1

    <br />

    Data4: @ViewBag.Data1

    <br />

    execution time:@ViewBag.time

     

     

    </div>

    public ActionResult Index()

    {

     

    Stopwatch stopWatch = new Stopwatch();

    stopWatch.Start();

     

    ViewBag.GetData1= GetData1();

    ViewBag.GetData2 = GetData2();

    ViewBag.GetData3 = GetData3();

    ViewBag.GetData4 = GetData4();

    stopWatch.Stop();

    ViewBag.btime = stopWatch.ElapsedMilliseconds;

    Stopwatch Watch = new Stopwatch();

     

    Watch.Start();

     

    Task<string> t1 = Task.Factory.StartNew<string>(GetData1);

    Task<string> t2 = Task.Factory.StartNew<string>(GetData2);

    Task<string> t3 = Task.Factory.StartNew<string>(GetData3);

    Task<string> t4 = Task.Factory.StartNew<string>(GetData4);

    Task.WaitAll(t1, t2, t3, t4);

     

     

    ViewBag.Data1 = t1.Result;

    ViewBag.Data2 = t2.Result;

    ViewBag.Data3 = t3.Result;

    ViewBag.Data4 = t4.Result;

    Watch.Stop();

    ViewBag.time = Watch.ElapsedMilliseconds;

     

     

    return View();

     

     

    }

     

     

    public string GetData1()

    {

    System.Threading.Thread.Sleep(1000);

    return "Content 1";

     

     

    }

     

    public string GetData2()

     

    {

     

     

    System.Threading.Thread.Sleep(1000);

    return "Content 1";

     

    }

     

    public string GetData3()

     

    {

    System.Threading.Thread.Sleep(1000);

    return "Content 4";

    }

     

    public string GetData4()

     

    {

    System.Threading.Thread.Sleep(1000);

    return "Content 1";

     

     

     

    }

     

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!