Skip to content

Commit

Permalink
Merge pull request #1908 from AntonyCorbett/cache-purge-contention
Browse files Browse the repository at this point in the history
Reduce purge contention at max cache size
  • Loading branch information
d2phap authored May 11, 2024
2 parents 1ce0893 + 17e58a2 commit 98166f8
Showing 1 changed file with 34 additions and 12 deletions.
46 changes: 34 additions & 12 deletions Source/Components/ImageGlass.Base/Cache/DiskCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,33 +269,55 @@ private void PurgeCache()
{
if (string.IsNullOrEmpty(_dirName)) return;
if (_cacheSize == 0) return;

if (_currentCacheSize <= _cacheSize) return;

var files = new DirectoryInfo(_dirName).GetFiles();
var indexList = new List<FileInfo>(files);

if (files.Length == 0) return;
// sort creation time ascending
indexList.Sort((f1, f2) =>
Array.Sort(files, (f1, f2) =>
{
var d1 = f1.CreationTime;
var d2 = f2.CreationTime;
return (d1 < d2 ? -1 : (d2 > d1 ? 1 : 0));
});

while (indexList.Count > 0 && _currentCacheSize > _cacheSize)
{
if (indexList.FirstOrDefault() is not FileInfo firstFile) continue;

_currentCacheSize -= firstFile.Length;
var filePath = firstFile.FullName;
// Reduce the cache to 50% of its maximum size. This way we prevent excessive
// purge operations when new items are subsequently added to the cache.
var maxPurgedSize = _cacheSize / 2;

indexList.RemoveAt(0);
firstFile.Delete();
foreach (var f in files)
{
if (!f.Exists) continue;

var length = f.Length;

if (TryDeleteFile(f))
{
_currentCacheSize -= length;
if (_currentCacheSize <= maxPurgedSize) break;
}
}

if (_currentCacheSize < 0) _currentCacheSize = 0;
}
}

private bool TryDeleteFile(FileInfo fi)
{
try
{
fi.Delete();
return true;
}
catch
{
// perhaps no access or IO exception
}

return false;
}

#endregion

}
Expand Down

0 comments on commit 98166f8

Please sign in to comment.