gpt4 book ai didi

c# - 异步方法中的 Console.ReadLine 不会阻止进程..?

转载 作者:太空狗 更新时间:2023-10-30 00:14:04 24 4
gpt4 key购买 nike

我需要知道是否有一种方法可以执行 DownloadPage(result) 而无需立即在我的 main 方法中继续执行 Console.ReadKey()。

发生的事情是 DownloadPage 触发,但在显示“Would you like to save this to a .txt file? [Y/N]”之后,程序在键入任意键后结束。我最初尝试了 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);
}
}
}
}

最佳答案

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

static async Task GetPageHtml(string _url)

然后在您的 Main 方法中等待它:

GetPageHtml(url).Wait();

现在通常,阻止任务像这样同步完成是一个坏主意,因为您最终可能会阻塞需要完成工作的同一个线程 - 但控制台应用程序的主线程不会”没有同步上下文,因此异步方法中的延续将在线程池线程中运行...因此此 Wait() 是安全的。

当然,这在某种程度上违背了使用异步的部分要点 - 但如果您只是探索异步,那很好。

一般来说,只有一次 async 方法应该被声明为void,这样您就可以将它用作事件处理程序。

关于c# - 异步方法中的 Console.ReadLine 不会阻止进程..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34238312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com