Run an async task in a console app and return a result
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("https://microsoft.com");
// return the value
return astr;
}
}
}
Drop me a note if this helped you out!