Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async parsing with AngleSharp

So I want to parse some data from website and I found a tutorial, here is code:

public static async void Test()
{
    var config = Configuration.Default.WithDefaultLoader();
    using var context = BrowsingContext.New(config);

    var url = "http://webcode.me";

    using var doc = await context.OpenAsync(url);
    // var title = doc.QuerySelector("title").InnerHtml;
    var title = doc.Title;

    Console.WriteLine(title);

    var pars = doc.QuerySelectorAll("p");

    foreach (var par in pars)
    {
        Console.WriteLine(par.Text().Trim());
    }
}

static void Main(string[] args)
{
    Test();
}

And the program quits right after it reaches the:

using var doc = await context.OpenAsync(url);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Nothing is waiting for your asynchronous method to complete, so the program quits. You can fix this by amending to use an async main method:

static Task Main(string[] args)
{
    return Test();
}

Or if you’re using a version older than C# 7.1 (where async main not supported):

static void Main(string[] args)
{
    Test().GetAwaiter().GetResult();
}

You’ll also need to change the return type of Test to async Task:

public static async Task Test()
{
    // ...
}

You might find the C# 7.1 docs on async main helpful.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading