Skip to content

Commit 7980b23

Browse files
committed
AsyncAtomicFactory.Initializer: do not call SetException on TCS to avoid unobserved task exception when garbage collecting TCS
1 parent 5b2d64a commit 7980b23

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

BitFaster.Caching.UnitTests/Atomic/AsyncAtomicFactoryTests.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,44 @@ public async Task WhenValueCreateThrowsValueIsNotStored()
7575
(await a.GetValueAsync(1, k => Task.FromResult(3))).Should().Be(3);
7676
}
7777

78+
[Fact]
79+
public async Task WhenValueCreateThrowsDoesNotCauseUnobservedTaskException()
80+
{
81+
bool unobservedExceptionThrown = false;
82+
83+
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
84+
try
85+
{
86+
await AsyncAtomicFactoryGetValueAsync();
87+
88+
GC.Collect();
89+
GC.WaitForPendingFinalizers();
90+
}
91+
finally
92+
{
93+
TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException;
94+
}
95+
unobservedExceptionThrown.Should().BeFalse();
96+
97+
void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
98+
{
99+
unobservedExceptionThrown = true;
100+
e.SetObserved();
101+
}
102+
103+
static async Task AsyncAtomicFactoryGetValueAsync()
104+
{
105+
var a = new AsyncAtomicFactory<int, int>();
106+
try
107+
{
108+
_ = await a.GetValueAsync(12, (i) => throw new ArithmeticException());
109+
}
110+
catch (ArithmeticException)
111+
{
112+
}
113+
}
114+
}
115+
78116
[Fact]
79117
public async Task WhenCallersRunConcurrentlyResultIsFromWinner()
80118
{

BitFaster.Caching/Atomic/AsyncAtomicFactory.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,9 @@ public async ValueTask<V> CreateValueAsync<TFactory>(K key, TFactory valueFactor
155155

156156
return value;
157157
}
158-
catch (Exception ex)
158+
catch (Exception)
159159
{
160160
Volatile.Write(ref isInitialized, false);
161-
tcs.SetException(ex);
162161
throw;
163162
}
164163
}

0 commit comments

Comments
 (0)