Scenario:
Run code AsyncSolution:
- Sync call
- Async call. The main thread is released but individual task still blocking
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | using System; using System.Threading.Tasks; namespace ConsoleApplication1 { class ProgramAsync { static async Task Main(string[] args) { Tea tea = PourTea(); Console.WriteLine("tea is ready"); var poha = await FryPohaAsync(2); //Poha poha = await pohaTask; Console.WriteLine("poha are ready"); var laddu = await MakeLadduAsync(3); //Laddu laddu = await ladduTask; Console.WriteLine("laddu are ready"); var toast = await ToastBreadAsync(2); //Toast toast = await toastTask; ApplyButter(toast); ApplyJam(toast); Console.WriteLine("toast is ready"); Juice mj = PourMJ(); Console.WriteLine("Mango juice is ready"); Console.WriteLine("Breakfast is ready!"); Console.Read(); } private static Juice PourMJ() { Console.WriteLine("Pouring Mango juice"); return new Juice(); } private static void ApplyJam(Toast toast) => Console.WriteLine("Putting jam on the toast"); private static void ApplyButter(Toast toast) => Console.WriteLine("Putting butter on the toast"); private static async Task<Toast> ToastBreadAsync(int slices) { for (int slice = 0; slice < slices; slice++) { Console.WriteLine("Putting a slice of bread in the toaster"); } Console.WriteLine("Start toasting..."); await Task.Delay(3000); Console.WriteLine("Remove toast from toaster"); return new Toast(); } private static async Task<Poha> FryPohaAsync(int ingrediants) { Console.WriteLine($"putting {ingrediants} ingrediants in kadhai"); Console.WriteLine("cooking in kadhai..."); await Task.Delay(3000); for (int ingrediant = 0; ingrediant < ingrediants; ingrediant++) { Console.WriteLine($"cooking ingrediant {ingrediant}"); } Console.WriteLine("steam poha.."); await Task.Delay(3000); Console.WriteLine("Put poha on plate"); return new Poha(); } private static async Task<Laddu> MakeLadduAsync(int howMany) { Console.WriteLine("Warming the pan..."); await Task.Delay(3000); Console.WriteLine($"make {howMany} laddu"); await Task.Delay(3000); Console.WriteLine("Put laddu on plate"); return new Laddu(); } private static Tea PourTea() { Console.WriteLine("Pouring tea"); return new Tea(); } } internal class Juice { } internal class Toast { } internal class Poha { } internal class Laddu { } internal class Tea { } } |
No comments:
Post a Comment