Home > DeveloperSection > Forums > How to Use System.Threading.Tasks in c# MVC.
Ankit Singh

Total Post:341

Points:2389
Posted on    November-01-2015 11:30 PM

 .NET C#  Mvc 
Ratings:


 1 Reply(s)
 434  View(s)
Rate this:
Can anyone please help me how to solve this problem.


aditya kumar Patel

Total Post:246

Points:1752
Posted on    November-01-2015 11:43 PM

  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";

 

 

 

}

 


Don't want to miss updates? Please click the below button!

Follow MindStick