Jeff Sanders Technical Blog

I am a Microsoft employee that has worked on all aspects of the Web Stack for a long time. I hope these blogs are useful to you! Use this information at your own risk.


<< Go Back

Run An Async Task In A Console App And Return A Result

- 07 Oct 2016

I had someone ask how to run an async task in Main of a console app.  Yes there are different ways to do it and this is just one!

 

using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace UrlAuth
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Start a task - calling an async function in this example
                Task<string> callTask = Task.Run(() => CallHttp());
                // Wait for it to finish
                callTask.Wait();
                // Get the result
                string astr = callTask.Result;
                // Write it our
                Console.WriteLine(astr);
            }
            catch (Exception ex)  //Exceptions here or in the function will be caught here
            {
                Console.WriteLine("Exception: " + ex.Message);
            }
        }
        // Simple async function returning a string...
        static public async Task<string> CallHttp()
        {
            // Just a demo.  Normally my HttpClient is global (see docs)
            HttpClient aClient = new HttpClient();
            // async function call we want to wait on, so wait
            string astr = await aClient.GetStringAsync("http://microsoft.com");
            // return the value
            return astr;
        }
    }
}

Drop me a note if this helped you out!

<< Go Back