异步方法中的Console.ReadLine是否阻止进展..?

时间:2015-12-12 09:27:00

标签: c#

我需要知道是否有一种方法可以执行DownloadPage(结果),而无需立即进入我的main方法中的Console.ReadKey()。

发生的事情是DownloadPage触发,但在显示&#34之后;您要将其保存为.txt文件吗? [是/否]",程序在输入任何键后结束。我最初在GetPageHTML中尝试了整个方法,但是一旦我尝试获取用户输入它就会一直破坏。

我还在学习C#而且我不知道如何解决问题并纠正它。有人可以帮忙吗?

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);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:8)

是的 - 你不是在等待异步操作真正完成。您应该声明方法返回Task,如下所示:

static async Task GetPageHtml(string _url)

然后在Main方法中等待它:

GetPageHtml(url).Wait();

现在正常,阻止某个任务同步完成,这是一个坏主意,因为你最终可能会阻止需要完成工作的同一个线程 - 但是控制台应用程序的主线程没有t有一个同步上下文,所以async方法中的continuation将在一个线程池线程中运行......所以这个Wait()是安全的。

当然,这在某种程度上打败了使用异步的一部分 - 但如果你只是在探索异步,那很好。

通常,时间async方法应声明为void,以便您可以将其用作事件处理程序。

答案 1 :(得分:3)

作为JonSkeet's回答的替代方法,您还可以使用StephenCleary's AsyncEx Library,然后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(); } 。所以你的代码看起来像这样:

<table class="table" style="margin-bottom: 0px;">
  <tr>
    <td> 
      [Facebook Share Button Code]
    </td>
    <td>
      [Google+ Share Button Code]
    </td>
    <td>
      [Twitter Tweet Link Code]
    </td>
  </tr>
</table>