diff --git a/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs b/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs
index 057d4621a..f9c303ef9 100644
--- a/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs
+++ b/src/Microsoft.VisualStudio.Threading/AsyncLazy`1.cs
@@ -298,7 +298,7 @@ public void DisposeValue()
///
///
/// Calling this method will put this object into a disposed state where future calls to obtain the value will throw .
- /// If the value has already been produced and implements , , or it will be disposed of.
+ /// If the value has already been produced and implements , , or it will be disposed of.
/// If the value factory has already started but has not yet completed, its value will be disposed of when the value factory completes.
/// If prior calls to obtain the value are in flight when this method is called, those calls may complete and their callers may obtain the value, although
/// may have been or will soon be called on the value, leading those users to experience a .
@@ -308,6 +308,7 @@ public void DisposeValue()
///
public async Task DisposeValueAsync()
{
+ JoinableTask? localJoinableTask = null;
Task? localValueTask = null;
object? localValue = default;
lock (this.syncObject)
@@ -331,6 +332,7 @@ public async Task DisposeValueAsync()
// We'll schedule the value for disposal outside the lock so it can be synchronous with the value factory,
// but will not execute within our lock.
localValueTask = this.value;
+ localJoinableTask = this.joinableTask;
break;
}
@@ -345,7 +347,11 @@ public async Task DisposeValueAsync()
this.valueFactory = null;
}
- if (localValueTask is not null)
+ if (localJoinableTask is not null)
+ {
+ localValue = await localJoinableTask;
+ }
+ else if (localValueTask is not null)
{
localValue = await localValueTask.ConfigureAwait(false);
}
diff --git a/test/Microsoft.VisualStudio.Threading.Tests/AsyncLazyTests.cs b/test/Microsoft.VisualStudio.Threading.Tests/AsyncLazyTests.cs
index 9c3e3981e..00027eecf 100644
--- a/test/Microsoft.VisualStudio.Threading.Tests/AsyncLazyTests.cs
+++ b/test/Microsoft.VisualStudio.Threading.Tests/AsyncLazyTests.cs
@@ -752,6 +752,31 @@ public async Task Dispose_CalledTwice_Disposable_Completed()
await this.AssertDisposedLazyAsync(lazy);
}
+ [Fact]
+ public void DisposeValue_MidFactoryThatContestsForMainThread()
+ {
+ JoinableTaskContext context = this.InitializeJTCAndSC();
+
+ AsyncLazy