C# .NET simple Async Await example from console application Main

I did a couple of posts a few years back about doing async/await in VB.NET, and now I had need of doing something similar with a C# .NET console application.

Here is what I put together to get it working. This is the contents of the main class for a C# .NET console application, but you should be able to adapt the code to whatever need you have.

using System;
using System.Net.Http;
using System.Threading.Tasks;
 
namespace SimpleAsync
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Simple async");
 
            try
            {
                LengthyAsyncTask().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was an exception: " + ex.ToString());
            }
 
            Console.WriteLine("Press enter to quit application...");
            Console.ReadLine();
        }
 
        static async Task LengthyAsyncTask()
        {
            var response = await GetWebPage("https://www.dosomethinghere.com");
            Console.WriteLine("Response: " + response);
            // do something here with the response
        }
 
        static async Task<string> GetWebPage(string url)
        {
            var client = new HttpClient();
            var response = await client.GetAsync(url);
            var responseString = await response.Content.ReadAsStringAsync();
            return responseString;
        }
    }
}

BTW, Happy Anniversary to The Wall and Thriller, both seminal works of artistry from music’s golden age, released this day in 1979 and 1982, respectively. Darkness falls across the land… And how can you eat your pudding when you haven’t eaten your meat?

2 Comments

  1. BP says:

    I did not see that, it sure would have come in handy when I needed it. Thanks for pointing it out.

Leave a Reply