dro*_*ros 6 c# command-line .net-core
我试图通过其 url 调用一个网站来构建网络爬虫,但是当我尝试从等待的 url 中获取项目时,我的应用程序停止并显示此消息:
blablah.exe (process 1512) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stop
Run Code Online (Sandbox Code Playgroud)
我不认为这是一个代码问题,也许是我的 Visual Studio 调试器的问题?因为我一生都看不到它是什么。
这是一个 .net core 命令行应用程序
一些代码以防万一
static void Main(string[] args)
{
GetHtmlAsync();
}
private static async void GetHtmlAsync()
{
var url = "https://blahblah.com";
var client = new HttpClient();
var html = await client.GetStringAsync(url);
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var newsList = htmlDoc.DocumentNode.Descendants("table")
.Where(node => node.GetAttributeValue("class","")
.Equals("itemList")).ToList();
Console.WriteLine(newsList);
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud)
调试时它甚至永远不会达到:
var htmlDoc = new HtmlDocument();
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
Tyl*_*ley 10
这里有几个问题
1)当您调用时GetHtmlAsync()
,您没有等待它,这意味着您的应用程序继续运行其后的代码(其中没有),导致应用程序退出
2)你应该避免 async void
除了事件处理程序之外,而是返回async Task
修改后的代码可能如下所示
static async Task Main(string[] args)
{
await GetHtmlAsync();
}
private static async Task GetHtmlAsync()
{
//Do stuff
}
Run Code Online (Sandbox Code Playgroud)
请注意,为了使用,async Task Main
您至少需要使用 C# 7.1
归档时间: |
|
查看次数: |
12843 次 |
最近记录: |