Console.ReadLine in an asynchronous method does not block progression.?

I need to know if there is a way to execute the DownloadPage (result) without immediately going to Console.ReadKey () in my main method.

What happens when DownloadPage starts, but after displaying "Do you want to save it in a .txt file? [Y / N]", the program ends after entering any key. At first I tried the whole method inside GetPageHTML, but it continues to break as soon as I try to get user input.

I am still learning C # and I don’t know how to approach the problem and fix it. Can anyone help?

using System;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;

namespace Programming_Challenge_4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter URL: ");
            string url = Console.ReadLine();

            GetPageHTML(url);
            Console.ReadKey();
        }

        static async void GetPageHTML(string _url)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(_url))
                using (HttpContent content = response.Content)
                {
                    string result = await content.ReadAsStringAsync();
                    string title = Regex.Match(result, @"<title>\s*(.*?)\s*</title>").Groups[1].Value;
                    Console.WriteLine("Downloading HTML...\n\nTitle: {0}\n\n{1}\n\n", title, result);
                    DownloadPage(result);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("There was an error reading the url \"{0}\".", _url);
            }
        }

        static void DownloadPage(string _html)
        {
            Console.WriteLine("Would you like to save this to a .txt file? [Y/N]");
            string saveFile = Console.ReadLine(); // CODE IS BREAKING HERE!

            if (saveFile.ToUpper() == "Y")
            {
                Console.Write("Please provide a file name: ");
                string name = Console.ReadLine();

                using (StreamWriter writer = new StreamWriter(name + ".txt"))
                {
                    writer.Write(_html);
                    writer.Close();
                }

                Console.WriteLine("HTML has been saved to {0}.txt!", name);
            }
        }
    }
}
+4
source share
2 answers

, async. Task, :

static async Task GetPageHtml(string _url)

Main:

GetPageHtml(url).Wait();

, , , , , , , , , async- ... Wait() .

, async - async, .

, async void, .

+8

JonSkeet StephenCleary AsyncEx, await GetPageHTML(). , :

using Nito.AsyncEx;    
static void Main(string[] args)
{
  AsyncContext.Run(() => MainAsync(args));
}        

static async void MainAsync(string[] args)
{
  Console.Write("Enter URL: ");
  string url = Console.ReadLine();

  await GetPageHTML(url);
  Console.ReadKey();
}
+3

Source: https://habr.com/ru/post/1619610/


All Articles