Run time error and Program exits when using - Async and await using C#

Viewed 423

I am trying to use the concept of async and await in my program. The program abruptly exits. I am trying to get the content length from few random urls and process it and display the size in bytes of each url.

Code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace TestProgram
{
    public class asyncclass
    {

        public async void  MainCall() {

             await SumPageSizes();

        }

        public async Task SumPageSizes(){

            List<string> urllist = GetUrlList();

            foreach (var url in urllist)
            {
                byte[] content = await GetContent(url);
                Displayurl(content, url);

            }


        }

        private void Displayurl(byte[] content, string url)
        {
            var length = content.Length;
            Console.WriteLine("The bytes length for the url response " + url + " is of :" +length );
        }

        private async Task<byte[]> GetContent(string url)
        {
            var content = new MemoryStream();

            try
            {


                var obj = (HttpWebRequest)WebRequest.Create(url);

                WebResponse response = obj.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    await stream.CopyToAsync(content);

                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);

            }

            return content.ToArray();
        }

        private List<string> GetUrlList()
        {
            var urllist = new List<string>(){
                "http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
                "http://msdn.microsoft.com",
                "http://msdn.microsoft.com/en-us/library/hh290136.aspx",
                "http://msdn.microsoft.com/en-us/library/ee256749.aspx",
                "http://msdn.microsoft.com/en-us/library/hh290138.aspx",
                "http://msdn.microsoft.com/en-us/library/hh290140.aspx",
                "http://msdn.microsoft.com/en-us/library/dd470362.aspx",
                "http://msdn.microsoft.com/en-us/library/aa578028.aspx",
                "http://msdn.microsoft.com/en-us/library/ms404677.aspx",
                "http://msdn.microsoft.com/en-us/library/ff730837.aspx"
            };
            return urllist;
        }
    }
}

Main

 public static void Main(string[] args)
        {
            asyncclass asyncdemo = new asyncclass();
            asyncdemo.MainCall();

        }
3 Answers
Related