Monday 7 May 2018

C# - Async - Task<> can prevent proliferation of async methods

I am just preparing a post on retired Microsoft C# exams, and I wanted to probe the Microsoft Learning web pages, so I wrote a little program to GET the HTML from a series of potential exam numbers. I did not want to hit Microsoft's server with multiple simultaneous requests because it is bad manners so I choose to run the series synchronously but the library has async methods only and I did not want a proliferation of async keywords as recommended by the compiler error message.

The answer is to use the Task class but you need to use a generic Task, that is Task<string> otherwise the Result property is not available. This isn't immediately obvious and so IMHO worth a blog post. The console code follows...

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace MicrosoftLearning
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 480; i <= 499; i++)
            {
                string html = readExam(i);
                using (var fil = System.IO.File.CreateText(@"n:\microsoftexams" + i.ToString() + ".html"))
                {
                    fil.Write(html);
                }
            }
        }

        public static string readExam(int lExamNum)
        {
            string html = "";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    string sUrl = "https://www.microsoft.com/en-gb/learning/exam-70-" + lExamNum.ToString() + ".aspx";
                    Task<string> tskGet = client.GetStringAsync(sUrl);
                    tskGet.Wait();
                    html = tskGet.Result;
                }
                catch (Exception ex)
                {

                    if (ex.InnerException.Message == "Response status code does not indicate success: 404 (Not Found).")
                    {
                        //bury the error
                    }
                    else
                    {
                        throw new Exception("unanticipated error:", ex);
                    }
                }
            }
            return html;
        }
    }
}

No comments:

Post a Comment