Make method asynchronous itself

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

Question

I use a technique 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;
}

To get the html source from a URL, I use HtmlAgilityPack.

However, using this strategy results in the freezing program.

When I use this function in UI BUT, I am aware that multithreading is possible. I want to build my technique such that when we use it, it operates without freezing (be responsive and asynchronous on its own).

I don't want to call my function with a thread or task because I don't want someone else's software to freeze if they use my method and don't understand multithreading.

1
5
9/4/2016 4:14:18 PM

Popular Answer

Typically, the proper approach would be toasync equivalents of the IO techniques you're using (such asLoad() ). But it seems that HtmlAgilityPack does not support async (at least not in its .Net 4.5 version).

Therefore, the best course of action is to execute your function on a different thread and mandate that callers utilizeasync -await :

The implementation may, for instance, 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));
}

not usingasync -await There is no effective way to prevent your procedure from blocking the thread that called it.

1
9/4/2016 11:55:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow