次の方法で共有


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!

Comments

  • Anonymous
    November 03, 2016
    I've been searching for a way to do this for two days now, and nothing I've found even works - plus most of the "solutions" are implausibly complicated (there's GOT to be a better way).This is the only thing I've found that works, and it's super easy. Thank you!...but I have to ask, are there any downsides to this technique?
    • Anonymous
      November 21, 2016
      Hi @MarkV. No there are no downsides to this technique!
  • Anonymous
    November 07, 2016
    There are other ways to do this, but for me this method is the easiest to implement and understand. It was just what I was looking for.
  • Anonymous
    January 13, 2017
    This helped me a great deal. I am no asychronous programming giant. However, I believe this was an earlier .net method of doing it. I tried starting an asynchronous method having a return type of Task using the newer await keyword in the Main method of a console application. The compiler reports: "Error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. It suggests to change the Main method to use the async keyword and then thinks all is well until you attempt to run the console app and it tells you: "error CS4009: an entry point cannot be marked with the 'async' modifier. Seems like the older method has some advantages. Thanks for the help