Skip to content

Instantly share code, notes, and snippets.

@majorsilence
Last active October 31, 2021 18:38
Show Gist options
  • Select an option

  • Save majorsilence/768f9575b92cf0f7158e134dbb52553b to your computer and use it in GitHub Desktop.

Select an option

Save majorsilence/768f9575b92cf0f7158e134dbb52553b to your computer and use it in GitHub Desktop.
Simple c# in memory cache. I have no idea if I built this or found it on the web somewhere. I find this interesting.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
namespace MajorSilence
{
public class SimpleCache
{
static ConcurrentDictionary<string, (string value, DateTime expires)> _cache = null;
public SimpleCache()
{
if (_cache == null)
{
_cache = new ConcurrentDictionary<string, (string value, DateTime expires)>();
}
}
public void SetValue(string key, string value, TimeSpan expires)
{
if (expires.TotalSeconds == 0) return;
_cache.AddOrUpdate(key, (value, DateTime.Now.AddMinutes(expires.TotalMinutes)), (k, o) => (value, DateTime.Now.AddMinutes(expires.TotalMinutes)));
}
public string GetValue(string key)
{
(string value, DateTime expires) outValue;
_cache.TryGetValue(key, out outValue);
if (!string.IsNullOrWhiteSpace(outValue.value))
{
TimeSpan span = outValue.expires.Subtract(DateTime.Now);
if (span.TotalSeconds < 0)
{
_cache.TryRemove(key, out outValue);
return null;
}
return outValue.value;
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment