using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; // created using // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/task-asynchronous-programming-model namespace AsyncAwait { internal class Program { static async Task Main(string[] args) { int result = await GetUrlContentLengthAsync(); Console.WriteLine("Hello World! string count = {0}", result); } static async public Task GetUrlContentLengthAsync() { var client = new HttpClient(); DoIndependentWork(); // 1. Aproach with Task Task getStringTask = client.GetStringAsync("https://docs.microsoft.com/dotnet"); string contents = await getStringTask; // 2. // Direct aproach //string contents = // await client.GetStringAsync("https://docs.microsoft.com/dotnet"); // 3. Do long syncronous job // var contents = DoLong(); // !!! Without await into the bory the method is syncronous // 4. Async ordinar long running method without async in the declaration // 4.1. DoLomg retuns void // Task result = await Task.Run(new Action(DoLong)); // if DoLong retuns void // 4.2. // string contents = await Task.Run(DoLong); Task returnedTaskTResult = GetTaskOfTResultAsync(); int intResult = await returnedTaskTResult; // Single line // int intResult = await GetTaskOfTResultAsync(); Task returnedTask = GetTaskAsync(); await returnedTask; // Single line await GetTaskAsync(); return contents.Length; } static void DoIndependentWork() { Console.WriteLine("Working..."); } // 3. //static string DoLong() // Even if the method is not declared async can be used as async with //{ // Thread.Sleep(10000); // return "Stoyan"; //} // 4.1. //static void DoLong() // Even if the method is not declared async can be used as async with //{ // Thread.Sleep(10000); // // return "Stoyan"; //} // 4.2. //static Task DoLong() // Even if the method is not declared async can be used as async with //{ // Thread.Sleep(10000); // // return "Stoyan"; // Task task = new Task(() => { return "Stoyan"; }) ; // return task; //} static async Task GetTaskOfTResultAsync() { int hours = 0; await Task.Delay(0); return hours; } static async Task GetTaskAsync() { await Task.Delay(0); // No return statement needed } } }