Bruno Lopes
Bruno Lopes

Reputation: 3056

Is AngleSharp's HtmlParser threadsafe?

Can I create a single private static readonly HtmlParser HtmlParser = new HtmlParser(); and use it safely across several threads?

Or should I create a parser per thread or per usage to avoid concurrency issues?

Upvotes: 5

Views: 632

Answers (2)

Michael Liu
Michael Liu

Reputation: 55389

I recommend that you create one HtmlParser per thread. Here’s why:

  1. As of AngleSharp version 1.0.0, HtmlParser derives from EventTarget, which contains mutable state and whose methods definitely aren’t thread safe. Intermittent errors may occur if one thread adds/removes event listeners while another thread parses HTML.
  2. The various Parse methods aren’t contractually guaranteed to be thread safe. Even if the methods happen to be thread safe today (ignoring the issue with events), they might become thread unsafe in a future release.
  3. Currently, HtmlParser doesn’t contain much state, so the cost of creating multiple instances is minimal.

Upvotes: 0

George Helyar
George Helyar

Reputation: 5278

From the source it looks like it should be thread safe. The object itself has no mutable state and creating a new HtmlParser with the default options each time doesn't seem to have any benefit over creating it once, so you should be able to treat it as a singleton. The only shared state is its configuration but the default constructor uses the default configuration, which is a singleton anyway.

That being said, there isn't a huge amount of benefit to treating it as a singleton. It avoids an allocation and cuts down on GC a bit but as it doesn't have an expensive constructor, the difference won't be huge.

Upvotes: 0

Related Questions