From e9f655212fb1d0fd828c9b6ac62e233cdebd4bba Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Wed, 14 Jun 2023 10:05:13 +0200 Subject: [PATCH] Use a blocking collection for SKTextBlob caching --- src/Skia/Avalonia.Skia/GlyphRunImpl.cs | 35 ++++++++++++-------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/src/Skia/Avalonia.Skia/GlyphRunImpl.cs b/src/Skia/Avalonia.Skia/GlyphRunImpl.cs index f6d84f0b12..fdb9d0b031 100644 --- a/src/Skia/Avalonia.Skia/GlyphRunImpl.cs +++ b/src/Skia/Avalonia.Skia/GlyphRunImpl.cs @@ -1,5 +1,6 @@ using System; using System.Buffers; +using System.Collections.Concurrent; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.TextFormatting; @@ -14,7 +15,7 @@ namespace Avalonia.Skia private readonly ushort[] _glyphIndices; private readonly SKPoint[] _glyphPositions; - private readonly Dictionary _textBlobCache = new(1); + private readonly ConcurrentDictionary _textBlobCache = new(); public GlyphRunImpl(IGlyphTypeface glyphTypeface, double fontRenderingEmSize, IReadOnlyList glyphInfos, Point baselineOrigin) @@ -100,32 +101,28 @@ namespace Avalonia.Skia break; } - if (_textBlobCache.TryGetValue(edging, out var textBlob)) + return _textBlobCache.GetOrAdd(edging, (_) => { - return textBlob; - } - - var font = _glyphTypefaceImpl.SKFont; + var font = _glyphTypefaceImpl.SKFont; - font.Hinting = SKFontHinting.Full; - font.Subpixel = edging == SKFontEdging.SubpixelAntialias; - font.Edging = edging; - font.Size = (float)FontRenderingEmSize; + font.Hinting = SKFontHinting.Full; + font.Subpixel = edging == SKFontEdging.SubpixelAntialias; + font.Edging = edging; + font.Size = (float)FontRenderingEmSize; - var builder = SKTextBlobBuilderCache.Shared.Get(); + var builder = SKTextBlobBuilderCache.Shared.Get(); - var runBuffer = builder.AllocatePositionedRun(font, _glyphIndices.Length); + var runBuffer = builder.AllocatePositionedRun(font, _glyphIndices.Length); - runBuffer.SetPositions(_glyphPositions); - runBuffer.SetGlyphs(_glyphIndices); + runBuffer.SetPositions(_glyphPositions); + runBuffer.SetGlyphs(_glyphIndices); - textBlob = builder.Build(); + var textBlob = builder.Build(); - SKTextBlobBuilderCache.Shared.Return(builder); + SKTextBlobBuilderCache.Shared.Return(builder); - _textBlobCache.Add(edging, textBlob); - - return textBlob; + return textBlob; + }); } public void Dispose()