From ef8fa26ed7c6e985b67d71461ac4b0db9563411d Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Fri, 30 Mar 2018 14:35:00 -0500 Subject: [PATCH] Fix race condition in Document.GetSemanticModelAsync Fixes #25836 --- .../Portable/Workspace/Solution/Document.cs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs index 4b470b8f4a3..2c4c96d85c2 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs @@ -276,15 +276,18 @@ public async Task GetSemanticModelAsync(CancellationToken cancell return result; } - // it looks like someone has set it. try to reuse same semantic model - if (original.TryGetTarget(out semanticModel)) + // It looks like someone has set it. Try to reuse same semantic model, or assign the new model if that + // fails. The lock is required since there is no compare-and-set primitive for WeakReference. + lock (original) { - return semanticModel; - } + if (original.TryGetTarget(out semanticModel)) + { + return semanticModel; + } - // it looks like cache is gone. reset the cache. - original.SetTarget(result); - return result; + original.SetTarget(result); + return result; + } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { -- GitLab