(Await +Async) and (task vs thread) :P
lets see so fun stuff
Use of Async and Await in a real world problem
while going through behind classes of ASP.NET mvc i found that async and await are used a lot.
i was not aware what is async and await.So i googled a bit and found out what kind of real world problems
this async and await solve.
Now there is an application in .NET which helps you to fetch information from three different database.
So when you click on “get info” button , there will be a blinker which will show busy sign till the time
information is received from all three sources.Once the information is received , the blinker will turn into
non busy sign.
Now before we go ahead we need to understand that when we create new task or thread function from our main thread,
the main thread will continue to do its work regardless what the new task is doing , so even if below code seems
to do job which we have coded it for — to run task 1 and then task 2 and then once both completed then print completed,
it will never reach completed status.At such time we use async and await
without async and await
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace _26102014tasklibrary
{ class Program { static void Main(string[] args) {
Boolean IsBusy = true; Task task1 = new Task(new Action(SaySomething)); Task task2 = new Task(new Action(RunMillionIterations)); task1.Start(); if(task1.IsCompleted == true) { task2.Start(); } if(task1.IsCompleted==true && task2.IsCompleted== true) { IsBusy = false; Console.WriteLine(“finished”); Console.ReadLine(); } else { Console.WriteLine(“finished”); Console.ReadLine(); } } public static void SaySomething() { for (int i = 0; i <= 100000; i++) { Console.WriteLine(“this is how we roll”); } } public static void RunMillionIterations() { Stopwatch stp = new Stopwatch(); stp.Start(); for (int i = 0; i <= 100000; i++) { Console.WriteLine(i); } stp.Stop(); TimeSpan ts = stp.Elapsed;
string elapsedTime = String.Format(“{0:00}:{1:00}:{2:00}.{3:00}”, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(“RunTime “ + elapsedTime); }
}
}
Now lets see how to add async and await to our code
//remember async and await are like husband and wife.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace _26102014tasklibrary
{ class Program { Boolean Isbusy; static void Main(string[] args) { Newasyncmethod(); Console.ReadLine(); //Boolean IsBusy = true;
//Task task1 = new Task(new Action(SaySomething)); //Task task2 = new Task(new Action(RunMillionIterations));
//task1.Start(); //if(task1.IsCompleted == true) //{ // task2.Start(); //} //if(task1.IsCompleted==true && task2.IsCompleted== true) //{ // IsBusy = false; // Console.WriteLine(“finished”); // Console.ReadLine(); //} //else //{ // Console.WriteLine(“finished”); // Console.ReadLine(); //} //Parallel.Invoke(() => SaySomething(), () => RunMillionIterations()); ////Thread O1 = new Thread(RunMillionIterations); ////O1.Start(); ////Parallel.For(0, 1, x => RunMillionIterations()); //Console.ReadLine(); }
public static async void Newasyncmethod() { await Task.Run(new Action(SaySomething)); await Task.Run(new Action(RunMillionIterations)); }
public static void SaySomething() { for (int i = 0; i <= 100000; i++) { Console.WriteLine(“this is how we roll”); } } public static void RunMillionIterations() { Stopwatch stp = new Stopwatch(); stp.Start(); for (int i = 0; i <= 100000; i++) { Console.WriteLine(i); } stp.Stop(); TimeSpan ts = stp.Elapsed;
string elapsedTime = String.Format(“{0:00}:{1:00}:{2:00}.{3:00}”, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(“RunTime “ + elapsedTime); }
}
}
so what is happening here is , we are stopping main thread to go ahead till child thread has performed its function.
This is very useful when you face problems mentioned above.
or we can use the Task.WhenAll() function , which waits for both the tasks to finish to move ahead
spinner.IsBusy = true;
try
{ Task t1 = Task.Run(() => dataX = loadX()); Task t2 = Task.Run(() => dataY = loadY()); Task t3 = Task.Run(() => dataZ = loadZ());
await Task.WhenAll(t1, t2, t3);
}
finally
{ spinner.IsBusy = false;
}
Tasks are upgrade from threads in c#
They are features of 4.5 Net framework and benefits of using tasks ahead of thread are as follows
You can consider a Task as a more sophisticated version of a Thread. They are very easy to use and have a lot of advantages over Threads as follows:
You can create return types to Tasks as if they are functions.
You can the “ContinueWith” method, which will wait for the previous task and then start the execution. (Abstracting wait)
You can use Task.WaitAll and pass an array of tasks so you can wait till all tasks are complete.
You can attach task to the parent task, thus you can decide whether the parent or the child will exist first.
You can achieve data parallelism with LINQ queries.
You can create parallel for and foreach loops
Very easy to handle exceptions with tasks.
*Most important thing is if the same code is run on single core machine it will just act as a single process without any overhead of threads.