Skip to content

Commit a8a0636

Browse files
More Race Condition Fixes (#28)
1 parent ef6bf5b commit a8a0636

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

src/Immediate.Cache.Shared/ApplicationCacheBase.cs

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -137,35 +137,32 @@ private Task<TResponse> GetHandlerTask()
137137
if (_responseSource is { Task: { Status: not (TaskStatus.Faulted or TaskStatus.Canceled) } task })
138138
return task;
139139

140+
task = (_responseSource = new()).Task;
141+
var cancellationTokenSource = _tokenSource = new();
142+
140143
// escape current sync context
141144
_ = Task.Factory.StartNew(
142-
RunHandler,
145+
o => RunHandler((CancellationTokenSource)o!),
146+
cancellationTokenSource,
143147
CancellationToken.None,
144148
TaskCreationOptions.PreferFairness,
145149
TaskScheduler.Current
146150
);
147151

148-
return (_responseSource = new()).Task;
152+
return task;
149153
}
150154
}
151155

152-
private async Task RunHandler()
156+
private async Task RunHandler(CancellationTokenSource tokenSource)
153157
{
154-
while (true)
158+
lock (_lock)
155159
{
156-
CancellationTokenSource tokenSource;
157-
158-
lock (_lock)
159-
{
160-
if (_responseSource?.Task is { IsCompletedSuccessfully: true })
161-
return;
162-
163-
if (_tokenSource is null or { IsCancellationRequested: true })
164-
_tokenSource = new();
165-
166-
tokenSource = _tokenSource;
167-
}
160+
if (_responseSource?.Task is { IsCompletedSuccessfully: true })
161+
return;
162+
}
168163

164+
while (true)
165+
{
169166
try
170167
{
171168
var token = tokenSource.Token;
@@ -202,6 +199,17 @@ private async Task RunHandler()
202199
return;
203200
}
204201
}
202+
203+
lock (_lock)
204+
{
205+
if (_responseSource is null or { Task.IsCompleted: true })
206+
return;
207+
208+
if (_tokenSource is null or { IsCancellationRequested: true })
209+
_tokenSource = new();
210+
211+
tokenSource = _tokenSource;
212+
}
205213
}
206214
}
207215

0 commit comments

Comments
 (0)