From 9fdaac8e660a608b988f3f3e3950555a3f0577e9 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Mon, 12 Sep 2022 21:19:35 +1000 Subject: [PATCH] Use Interlocked.CompareExchange --- tests/ImageSharp.Tests/TestFile.cs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/tests/ImageSharp.Tests/TestFile.cs b/tests/ImageSharp.Tests/TestFile.cs index ed5c4a0f09..730a5e91d9 100644 --- a/tests/ImageSharp.Tests/TestFile.cs +++ b/tests/ImageSharp.Tests/TestFile.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Concurrent; using System.IO; +using System.Threading; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.PixelFormats; @@ -29,7 +30,7 @@ namespace SixLabors.ImageSharp.Tests /// /// The image (lazy initialized value) /// - private Image image; + private volatile Image image; /// /// The image bytes @@ -65,7 +66,28 @@ namespace SixLabors.ImageSharp.Tests /// /// Gets the image with lazy initialization. /// - private Image Image => this.image ??= ImageSharp.Image.Load(this.Bytes); + private Image Image + { + get + { + Image img = this.image; + if (img is null) + { + Image loadedImg = ImageSharp.Image.Load(this.Bytes); + img = Interlocked.CompareExchange(location1: ref this.image, value: loadedImg, comparand: null); + if (img is not null) + { + loadedImg.Dispose(); + } + else + { + img = loadedImg; + } + } + + return img; + } + } /// /// Gets the input image directory.