Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed lazy loading thread safety #35529

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

henriquewr
Copy link

Added sync for lazy loading

Fixes #35528

 - Added sync for lazy loading

Fixes dotnet#35528
@henriquewr henriquewr requested a review from a team as a code owner January 25, 2025 03:45
@henriquewr
Copy link
Author

@dotnet-policy-service agree

@AndriySvyryd AndriySvyryd self-assigned this Jan 25, 2025
@roji roji changed the title Fixed #35528 Fixed lazy loading thread safety Jan 25, 2025
var willWait = true;
TaskCompletionSource taskCompletionSource;

lock (_isLoadingLock)
Copy link
Author

@henriquewr henriquewr Jan 25, 2025

Choose a reason for hiding this comment

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

As in the last commit I already did a thread sync in the ConcurrentDictionary
I changed to use the normal Dictionary, and instead of GetOrAdd i use a slightly faster approach

changing that makes it about 15% faster

Added tests for lazy loading thread safety
@AndriySvyryd AndriySvyryd requested a review from Copilot January 29, 2025 19:19

Choose a reason for hiding this comment

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

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

@AndriySvyryd
Copy link
Member

@henriquewr Could you explain what the issue in the original code was? It seems that it made some incorrect assumption, but I don't see what it was exactly

@AndriySvyryd
Copy link
Member

Oh, I see. While it prevented a second thread from loading it didn't make it wait for the first thread to finish.

@henriquewr
Copy link
Author

@AndriySvyryd Exacly that what i was going to say


if (exists)
{
if (isLoadingValue.Depth.Value == 1)
Copy link
Member

Choose a reason for hiding this comment

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

This is an interesting optimization. It definitely warrants a comment on how it works as the next person to read this code will be very confused.

@roji @cincuranet What's your opinion of this usage of AsyncLocal?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Lazy loading is not thread safe
2 participants