Thread and task Vs async and Await
What is the deference between task and async and await (introduced in .net 4) and what is async method?
Sync method replaces the use of thread or task (tpl) with one obverse difference:
In sync method that has an await in it, the thread that called the sync function will be the one that will start it unlike in a thread or a task when a new task will start the function
Using async and await is thread when you work in gui related environments like WPF of windows forms when only the ui thread can perform the changes to the ui, in this cases the ui thread won't be blocked while calling the awit
Async await example:
- static void Main(string[] args)
- {
- var returningTask = someFunctionAsync();
-
- Console.WriteLine("Doing some work for 5 seconds in main");
- Thread.Sleep(5000);
- Console.WriteLine("Main function was finished by thread number {0}",Thread.CurrentThread.ManagedThreadId);
- Console.ReadKey();
- }
-
- static async Task<int> someFunctionAsync()
- {
- Console.WriteLine("Starting async function on thread number {0}",
- Thread.CurrentThread.ManagedThreadId);
- await Task.Delay(3000);
- Console.WriteLine("Asyc function was finished by thread number {0}",
- Thread.CurrentThread.ManagedThreadId);
- return 101;
- }
The output:
You can see that the starting thread of main is 9 and it is also the finishing thread of main.
Thread 9 is also the thread that is starting the async function.
When the await in async function in line 15 begins thread 9 goes to do other work and thread 6 will be the thread that will finish the async function.
Task example:
- static void Main(string[] args)
- {
- var task = Task.Factory.StartNew<int>(someFunction);
- Console.WriteLine("Main function was started by thread number {0}", Thread.CurrentThread.ManagedThreadId);
- Console.WriteLine("Doing some work for 5 seconds in main");
- Thread.Sleep(5000);
- Console.WriteLine("Main function was finished by thread number {0}", Thread.CurrentThread.ManagedThreadId);
- Console.ReadKey();
- }
-
- static int someFunction()
- {
- Console.WriteLine("Starting someFunction on thread number {0}",
- Thread.CurrentThread.ManagedThreadId);
- Thread.Sleep(3000);
- Console.WriteLine("SomeFunction was finished by thread number {0}",
- Thread.CurrentThread.ManagedThreadId);
- return 101;
- }
The output
In this example we can see that the thread that started and finished main was 8.
The thread that started someFunction was a new thread, unlike the async function, and the thread that finished the someFunction was thread 9 so actually thread 9 was idol the hall time that it was sleeping in line 15.