Код консольного приложения C # не выполняется после ожидания - PullRequest
0 голосов
/ 08 июня 2018

Я пытаюсь создать веб-браузер, где я получаю все ссылки для загрузки css / js / images из файла html.

Проблема

Первая точка останова срабатывает, но вторая не после нажатия «Продолжить».

Изображение в Visual Studio

Код, о котором я говорю:

  private static async void GetHtml(string url, string downloadDir)
    {

        //Get html data, create and load htmldocument 
        HttpClient httpClient = new HttpClient();

        //This code gets executed
        var html = await httpClient.GetStringAsync(url);

        //This code not
        Console.ReadLine();
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(html);

        //Get all css download urls
        var linkUrl = htmlDocument.DocumentNode.Descendants("link")
            .Where(node => node.GetAttributeValue("type", "")
            .Equals("text/css"))
            .Select(node=>node.GetAttributeValue("href",""))
            .ToList();

        //Downloading css, js, images and source code
        using (var client = new WebClient())
        {
            for (var i = 0; i <scriptUrl.Count; i++)
            {

                    Uri uri = new Uri(scriptUrl[i]);
                    client.DownloadFile(uri,
                    downloadDir + @"\js\" + uri.Segments.Last());

            }
        }

Редактировать

Я вызываю метод getHtml отсюда:

    private static void Start()
    {
        //Create a list that will hold the names of all the subpages
        List<string> subpagesList = new List<string>();

        //Ask user for url and asign that to var url, also add the url to the url list
        Console.WriteLine("Geef url van de website:");
        string url = "https://www.hethwc.nl";


        //Ask user for download directory and assign that to var downloadDir
        Console.WriteLine("Geef locatie voor download:");
        var downloadDir = @"C:\Users\Daniel\Google Drive\Almere\C# II\Download tests\hethwc\";

        //Download and save the index file
        var htmlSource = new System.Net.WebClient().DownloadString(url);
        System.IO.File.WriteAllText(@"C:\Users\Daniel\Google Drive\Almere\C# II\Download tests\hethwc\index.html", htmlSource);

        // Creating directories 
        string jsDirectory = System.IO.Path.Combine(downloadDir, "js");
        string cssDirectory = System.IO.Path.Combine(downloadDir, "css");
        string imagesDirectory = System.IO.Path.Combine(downloadDir, "images");

        System.IO.Directory.CreateDirectory(jsDirectory);
        System.IO.Directory.CreateDirectory(cssDirectory);
        System.IO.Directory.CreateDirectory(imagesDirectory);

        GetHtml("https://www.hethwc.nu", downloadDir);
    }

1 Ответ

0 голосов
/ 08 июня 2018

Как вы звоните GetHtml?Предположительно это из метода sync Main, и у вас нет другого неработающего потока в игре (потому что ваш основной поток завершился): процесс завершится.Что-то вроде:

static void Main() {
    GetHtml();
}

Вышеуказанное прекратит процесс сразу после возврата GetHtml и завершения метода Main, который будет в первой неполной точке await.

В текущих версиях C # (C # 7.1 и далее) вы можете создать метод async Task Main(), который позволит вам правильно await ваш GetHtml метод, если вы измените GetHtml для возврата Task:

async static Task Main() {
    await GetHtml();
}
...