// --------------------------------------------------------------------------------------------------------------------
//
// Copyright (c) James South.
// Licensed under the Apache License, Version 2.0.
//
//
// Represents an in memory collection of keys and values whose operations are concurrent.
//
// --------------------------------------------------------------------------------------------------------------------
namespace ImageProcessor.Web.Caching
{
#region Using
using System.Collections.Generic;
using System.IO;
using System.Runtime.Caching;
using System.Threading.Tasks;
using ImageProcessor.Web.Helpers;
#endregion
///
/// Represents an in memory collection of keys and values whose operations are concurrent.
///
internal static class CacheIndexer
{
#region Public
///
/// Gets the associated with the specified key.
///
///
/// The cached path of the value to get.
///
///
/// The matching the given key if the contains an element with
/// the specified key; otherwise, null.
///
public static async Task GetValueAsync(string cachedPath)
{
string key = Path.GetFileNameWithoutExtension(cachedPath);
CachedImage cachedImage = (CachedImage)MemCache.GetItem(key);
if (cachedImage == null)
{
cachedImage = await TaskHelpers.Run(() => GetCachedImage(cachedPath));
if (cachedImage != null)
{
Add(cachedImage);
}
}
return cachedImage;
}
///
/// Removes the value associated with the specified key.
///
///
/// The key of the item to remove.
///
///
/// true if the removes an element with
/// the specified key; otherwise, false.
///
public static bool Remove(string cachedPath)
{
string key = Path.GetFileNameWithoutExtension(cachedPath);
return MemCache.RemoveItem(key);
}
///
/// Adds the specified key and value to the dictionary or returns the value if it exists.
///
///
/// The cached image to add.
///
///
/// The value of the item to add or get.
///
public static CachedImage Add(CachedImage cachedImage)
{
// Add the CachedImage.
CacheItemPolicy policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List { cachedImage.Path }));
MemCache.AddItem(cachedImage.Key, cachedImage, policy);
return cachedImage;
}
#endregion
///
/// Creates a new cached image from the cache instance on disk.
///
///
/// The cache path.
///
///
/// The from the cache instance on disk.
///
private static CachedImage GetCachedImage(string cachePath)
{
// FileInfo is thread safe.
FileInfo fileInfo = new FileInfo(cachePath);
if (!fileInfo.Exists)
{
return null;
}
// Pull the latest info.
fileInfo.Refresh();
return new CachedImage
{
Key = Path.GetFileNameWithoutExtension(cachePath),
Path = cachePath,
LastWriteTimeUtc = fileInfo.LastWriteTimeUtc
};
}
}
}