diff --git a/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs b/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs index 013f96fa2..1f9c3ae6f 100644 --- a/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs +++ b/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs @@ -224,6 +224,10 @@ public Task GetValueAsync(CancellationToken cancellationToken) // to synchronously block the Main thread waiting for the result // without leading to deadlocks. this.joinableTask = this.jobFactory.RunAsync(valueFactory); + + // this ensures that this.joinableTask must be committed before this.value + Thread.MemoryBarrier(); + this.value = this.joinableTask.Task; } else @@ -245,6 +249,9 @@ public Task GetValueAsync(CancellationToken cancellationToken) resumableAwaiter?.Resume(); } + // this ensures that this.joinableTask cannot be retrieved before the conditional check using this.value + Thread.MemoryBarrier(); + return this.joinableTask?.JoinAsync(continueOnCapturedContext: false, cancellationToken) ?? this.value.WithCancellation(cancellationToken); }