// void async is bad // exception in async void will cause the whole methid to give exception and application to crash //private async void MethodToBeExecutedAsyncCrash() private async Task MethodToBeExecutedAsyncNoCrash() { var _rep = new ClassCoffee(); // create a new object var result = await _rep.GetValueAsync(); // asked and awaited from cofee object repository throw new Exception(message: "Something failed"); Console.WriteLine($"result is: {result}"); //using try{}catch(){} will avoid the error }
/*actions:1.Pour a cup of coffee. * 2.Heat up a pan, then fry two eggs. * 3.Fry three slices of bacon. * 4.Toast two pieces of bread. * 5.Add butter and jam to the toast. * 6.Pour a glass of orange juice. */ static async Task Main(string[] args) { MyLibrary.AsyncUnitTesting(); ClassCoffee cup = PourCoffee(); Console.WriteLine("coffee is ready"); Task <ClassEgg> eggsTask = FryEggsAsync(2); Task <ClassBacon> baconTask = FryBaconAsync(3); Task <ClassToast> toastTask = MakeToastWithButterAndJamAsync(2); // tasks started to execute var breakfastTasks = new List <Task> { eggsTask, baconTask, toastTask }; while (breakfastTasks.Count > 0) { //// WhenAll returns a Task that completes when all the tasks in its argument list have completed //await Task.WhenAll(eggsTask, baconTask, toastTask); // WhenAny returns a Task<Task> that completes when any of its arguments completes // one task from list finished execution Task finishedTask = await Task.WhenAny(breakfastTasks); if (finishedTask == eggsTask) { Console.WriteLine("eggs are ready"); } else if (finishedTask == baconTask) { Console.WriteLine("bacon is ready"); } else if (finishedTask == toastTask) { Console.WriteLine("toast is ready"); } breakfastTasks.Remove(finishedTask); } ClassJuice oj = PourOJ(); Console.WriteLine("oj is ready"); Console.WriteLine("Breakfast is ready!"); }