what is the cause for my console app exiting with code 0?

Viewed 6242

I'm trying to call a site via its url to build a webscraper, but when i try to grab the items from the awaited url my application stops and brings up this message:

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

I dont think this is a code issue, perhaps something with my visual studio debugger? for the life of me can't see what it is.

This is a .net core command line app

Some code just in-case

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


    }
}

when debugging it never even reaches:

var htmlDoc = new HtmlDocument();

any ideas?

2 Answers

There are a couple problems here

1) When you call GetHtmlAsync() you are not awaiting it, meaning your application continues to run the code after it (of which there is none), leading to the app exiting

2) You should avoid async void except for event handlers, instead return async Task

Modified code might look like this

static async Task Main(string[] args)
{
    await GetHtmlAsync();
}

private static async Task GetHtmlAsync()
{
  //Do stuff
}

Note that in order to use async Task Main you need to be using at least C# 7.1

The reason it's returning 0 (zero), success, is because it exited without error.

Change the method to:

private static async Task GetHtmlAsync()

And call it like this:

GetHtmlAsync().Wait();

The method will run synchronously, but the app does anyway, as written.

Related