Skip to content

[Refactoring] - use ConcurrentDictionary in font caches#330

Open
Stepami wants to merge 15 commits intoempira:masterfrom
Stepami:refactoring/cache-locks-apply
Open

[Refactoring] - use ConcurrentDictionary in font caches#330
Stepami wants to merge 15 commits intoempira:masterfrom
Stepami:refactoring/cache-locks-apply

Conversation

@Stepami
Copy link

@Stepami Stepami commented Jan 13, 2026

Problem

Different font info caches use Dictionary as a data store. To ensure exclusive access to this caches Monitor is used through Locks.EnterFontFactory. To me this looks as "hello world" example of refactoring to ConcurrentDictionary. The benefits of this data structure are obviously benefitting:

  • lock-free read
  • fine-grained lock write

Measurements

Inside Stepami#1 I measured benefit of my refactoring with BenchmarkDotNet. Here are the results:

BenchmarkDotNet v0.15.8, Windows 10 (10.0.19045.6456/22H2/2022Update)
12th Gen Intel Core i7-12650H 2.30GHz, 1 CPU, 16 logical and 10 physical cores
.NET SDK 10.0.100
  [Host]   : .NET 8.0.12 (8.0.12, 8.0.1224.60305), X64 RyuJIT x86-64-v3
  .NET 8.0 : .NET 8.0.12 (8.0.12, 8.0.1224.60305), X64 RyuJIT x86-64-v3

Job=.NET 8.0  Runtime=.NET 8.0  
Method Iterations Mean Error StdDev Ratio RatioSD
LockFactory 1 18.893 ns 0.3760 ns 0.3693 ns 1.00 0.03
ConcurrentDictionary 1 9.853 ns 0.2187 ns 0.2045 ns 0.52 0.01
LockFactory 10 199.355 ns 2.9471 ns 2.7567 ns 1.00 0.02
ConcurrentDictionary 10 92.248 ns 1.0529 ns 0.9849 ns 0.46 0.01
LockFactory 100 1,948.679 ns 33.7892 ns 26.3804 ns 1.00 0.02
ConcurrentDictionary 100 969.329 ns 12.6024 ns 11.1717 ns 0.50 0.01

@ThomasHoevel
Copy link
Member

To me this looks as "hello world" example of refactoring to ConcurrentDictionary.

With PDFsharp, one lock synchronizes access to several dictionaries, so they all are either locked or in a valid state.
With your proposed changes, a new font might be registered in one dictionary by one thread which is then suspended - and another thread might register it in another dictionary.
With other words: We have doubts that your changes really work in multi-threaded tasks, e.g. a web server creating PDF files.

The locks can all be safely removed in a single-thread single-task environment. But they are needed for web server use.
Your benchmarks do not prove that your changes are safe.

@ThomasHoevel ThomasHoevel added enhancement New feature or request investigation Under investigation labels Feb 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request investigation Under investigation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants