Created
March 11, 2018 14:07
-
-
Save asarnaout/dcb9173958aa1c002024f41d79631b66 to your computer and use it in GitHub Desktop.
Async/Await Tutorial in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
DoSomethingAsync(); | |
Console.ReadLine(); | |
} | |
public static async void DoSomethingAsync() | |
{ | |
Console.WriteLine("Entering the main calling function"); | |
var task = ExpensiveOperation(); | |
//When "ExpensiveOperation" awaits the task, the running thread will return to this point and continue execution. | |
Console.WriteLine("Concurrent thread is now running in the background"); | |
await task; //At this point, the running thread will return to the thread pool. | |
Console.WriteLine("Operation completed"); //This will execute after the task is completed | |
} | |
public static async Task<bool> ExpensiveOperation() | |
{ | |
Console.WriteLine("Entering sub-function"); | |
/* | |
* Using the await keyword, you indicate that any operation following the awaited task is a continuation to the | |
* task. | |
* | |
* At this point, the current thread will return to the calling method (and in case the calling method is awaiting | |
* this task, then the current thread will return to the thread pool) until the awaited task is completed / returns, | |
* then a background thread will be assigned to serve the continuation | |
*/ | |
var response = await Task.Run(() => | |
{ | |
Thread.Sleep(5000); | |
Console.WriteLine("Concurrent thread will return now"); | |
return true; | |
}); | |
//The below is a continuation to the above task that will run when the task returns | |
Console.WriteLine("Task completed"); | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment