Make TestFile Image threadsafe.#2225
Merged
JimBobSquarePants merged 3 commits intomainfrom Sep 14, 2022
Merged
Conversation
br3aker
reviewed
Sep 13, 2022
tests/ImageSharp.Tests/TestFile.cs
Outdated
| Image<Rgba32> img = this.image; | ||
| if (img is null) | ||
| { | ||
| Image<Rgba32> loadedImg = ImageSharp.Image.Load<Rgba32>(this.Bytes); |
Contributor
There was a problem hiding this comment.
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?
Member
Author
There was a problem hiding this comment.
Definitely far more readable. I’m happy to switch out
br3aker
reviewed
Sep 13, 2022
tests/ImageSharp.Tests/TestFile.cs
Outdated
| /// <summary> | ||
| /// Used to ensure image loading is threadsafe. | ||
| /// </summary> | ||
| private readonly object syncLock; |
Contributor
There was a problem hiding this comment.
Suggested change
| private readonly object syncLock; | |
| private readonly object syncLock = new(); |
Member
Author
There was a problem hiding this comment.
Ha! Can't believe I missed that!
brianpopow
approved these changes
Sep 13, 2022
This was referenced Sep 29, 2025
This was referenced Nov 17, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prerequisites
Description
Fix #2178
CC @br3aker