0

I'm trying to get a hang of async-await methods but I'm really not getting the hang of it. I previously used WebRequest, which is really simple but sadly is synchronous.

My problem is that StartTest() is not running -- "Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call'. I can't add await before as the parent method is Main, and it can't of course be an async method. I realize my understanding of async is horrible -- could anyone point me in the right way?

static void Main(string[] args)
    {
        StartTest();

        async Task<string> StartTest()
        {
            using (var client = new HttpClient())
            {
                List<string> urls = new List<string> { //a list of urls i want to check };

                if (await GetStatusCodes(urls) != true)
                {
                    return "NOT OK";
                }
            }

            return "OK";

        }


        async Task<bool> GetStatusCodes(IList<string> urls)
        {
            using (var client = new HttpClient())
            {
                foreach (var url in urls)
                {
                    var response = await client.GetAsync(url);
                    if (response.StatusCode.ToString() != "OK")
                    {
                        return false;
                    }
                }

                return true;
            }
        }
    }

1 Answers1

0

You can make a MainAsync method put stuff in that you want to run async.

e.g.

private static void Main()
{
    MainAsync().Wait();
}
private static async Task MainAsync()
{
    // do async stuff
}
Stuart
  • 3,949
  • 7
  • 29
  • 58