Skip to content

Commit f804401

Browse files
committed
If the writer lock isn't immediately available, then assume another worker could have processed the request while we were waiting for the lock, so recheck the cache
1 parent 4a37d3f commit f804401

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/ImageSharp.Web/Middleware/ImageSharpMiddleware.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,8 +291,23 @@ private async Task ProcessRequestAsync(
291291
RecyclableMemoryStream outStream = null;
292292
try
293293
{
294-
using (await this.asyncKeyLock.WriterLockAsync(key))
294+
Task<AsyncReaderWriterLock.Releaser> takeLockTask = this.asyncKeyLock.WriterLockAsync(key);
295+
bool lockWasAlreadyHeld = takeLockTask.Status != TaskStatus.RanToCompletion;
296+
using (await takeLockTask)
295297
{
298+
// If the lock was already held, then that means there's a chance another worker has already
299+
// processed this same request and the value may now be available in the cache, so check
300+
// the cache one more time
301+
if (lockWasAlreadyHeld)
302+
{
303+
readResult = await this.IsNewOrUpdatedAsync(sourceImageResolver, key);
304+
if (!readResult.IsNewOrUpdated)
305+
{
306+
await this.SendResponseAsync(imageContext, key, readResult.CacheImageMetadata, readResult.Resolver, null);
307+
return;
308+
}
309+
}
310+
296311
try
297312
{
298313
ImageCacheMetadata cachedImageMetadata = default;

0 commit comments

Comments
 (0)