Skip to content

Commit b82caef

Browse files
committed
Ambient exceptions: store on an AsyncLocal<T> for test isolation
1 parent 486f03f commit b82caef

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

StackExchange.Redis.Tests/TestBase.cs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,13 @@ static TestBase()
6262
#if NETCOREAPP1_0
6363
if (IgnorableExceptionPredicates.Any(predicate => predicate(args.Exception.InnerException))) return;
6464
#endif
65-
Interlocked.Increment(ref sharedFailCount);
65+
lock (sharedFailCount)
66+
{
67+
if (sharedFailCount != null)
68+
{
69+
sharedFailCount.Value++;
70+
}
71+
}
6672
lock (backgroundExceptions)
6773
{
6874
backgroundExceptions.Add(args.Exception.ToString());
@@ -97,7 +103,7 @@ protected void OnInternalError(object sender, InternalErrorEventArgs e)
97103
}
98104

99105
private int privateFailCount;
100-
private static int sharedFailCount;
106+
private static AsyncLocal<int> sharedFailCount = new AsyncLocal<int>();
101107
private volatile int expectedFailCount;
102108

103109
private static readonly List<string> privateExceptions = new List<string>();
@@ -107,7 +113,10 @@ public void ClearAmbientFailures()
107113
{
108114
Collect();
109115
Interlocked.Exchange(ref privateFailCount, 0);
110-
Interlocked.Exchange(ref sharedFailCount, 0);
116+
lock (sharedFailCount)
117+
{
118+
sharedFailCount.Value = 0;
119+
}
111120
expectedFailCount = 0;
112121
lock (privateExceptions)
113122
{
@@ -136,7 +145,13 @@ private static void Collect()
136145
public void Teardown()
137146
{
138147
Collect();
139-
if (expectedFailCount >= 0 && (Interlocked.CompareExchange(ref sharedFailCount, 0, 0) + privateFailCount) != expectedFailCount)
148+
int sharedFails;
149+
lock (sharedFailCount)
150+
{
151+
sharedFails = sharedFailCount.Value;
152+
sharedFailCount.Value = 0;
153+
}
154+
if (expectedFailCount >= 0 && (sharedFails + privateFailCount) != expectedFailCount)
140155
{
141156
lock (privateExceptions)
142157
{

0 commit comments

Comments
 (0)