Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions tests/ImageSharp.Tests/TestFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -29,7 +30,7 @@ public sealed class TestFile
/// <summary>
/// The image (lazy initialized value)
/// </summary>
private Image<Rgba32> image;
private volatile Image<Rgba32> image;

/// <summary>
/// The image bytes
Expand Down Expand Up @@ -65,7 +66,28 @@ public sealed class TestFile
/// <summary>
/// Gets the image with lazy initialization.
/// </summary>
private Image<Rgba32> Image => this.image ??= ImageSharp.Image.Load<Rgba32>(this.Bytes);
private Image<Rgba32> Image
{
get
{
Image<Rgba32> img = this.image;
if (img is null)
{
Image<Rgba32> loadedImg = ImageSharp.Image.Load<Rgba32>(this.Bytes);
Copy link
Contributor

@br3aker br3aker Sep 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, we can do a double check lock instead so image would never be loaded twice:

// this.image should be marked volatile still
if (this.image is null)
{
    lock (this.lockObject)
    {
        if (this.image is null)
        {
            this.image = ImageSharp.Image.Load<Rgba32>(this.Bytes);
        }
    }
}
return this.image;

I proposed Interlocked solution, I know, but lock solution is a lot more readable IMO and doesn't have a possible flaw of loading the same image twice. It's also isn't slow on reads due to locking as most of the time first if check would be true.

Maybe we should use it instead due to simplicity?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely far more readable. I’m happy to switch out

img = Interlocked.CompareExchange(location1: ref this.image, value: loadedImg, comparand: null);
if (img is not null)
{
loadedImg.Dispose();
}
else
{
img = loadedImg;
}
}

return img;
}
}

/// <summary>
/// Gets the input image directory.
Expand Down