Make method asynchronous itself

async-await asynchronous c# html-agility-pack multithreading

Question

I have a method like this:

public  List<List<string>>  GroupedNodes(string URL, params string[] XPathes)
{
    //Load HTML Source
    HtmlWeb loader = new HtmlWeb();
    HtmlAgilityPack.HtmlDocument doc = loader.Load(URL);

    //some other codes ...

    //Return result as a List of list
    return grouped;
}

I use HtmlAgilityPack to get html source from an url.

But when I use this method it causes freezing program.

I know I can use multithreading when I call this method in UI BUT I want to write my method in a way to be asynchronous & Responsive itself and when we use it, it works without freezing.

I mean if someone use my method and he/she don't know multithreading ,I want his/her program not to freeze, in the other words, I don't want to call my Method with a thread or task!

Popular Answer

Normally, the right way would be use async equivalents of the IO methods that you're using (like Load()). But HtmlAgilityPack does not seem to support async (at least not in its .Net 4.5 version).

This means the best option is to run your method on another thread and require callers to use async-await:

For example, the implementation could look like this:

private List<List<string>> GroupedNodes(string URL, params string[] XPathes)
{
    //Load HTML Source
    HtmlWeb loader = new HtmlWeb();
    HtmlAgilityPack.HtmlDocument doc = loader.Load(URL);

    //some other codes ...

    //Return result as a List of list
    return grouped;
}

public Task<List<List<string>>> GroupedNodesAsync(string URL, params string[] XPathes)
{
    return Task.Run(() => GroupedNodes(URL, XPathes));
}

Without using async-await, there is no good way to make your method not block the calling thread.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why