Skip to content

Instantly share code, notes, and snippets.

@sebingel
Created August 29, 2017 15:23
Show Gist options
  • Save sebingel/561faff165180f4e1cba39d88718d304 to your computer and use it in GitHub Desktop.
Save sebingel/561faff165180f4e1cba39d88718d304 to your computer and use it in GitHub Desktop.
Short example of MemoryCache
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
namespace CacheTest
{
internal class Program
{
private UnitRepo _unitrepo;
private static void Main()
{
new Program().Run();
}
private void Run()
{
_unitrepo = new UnitRepo();
Console.WriteLine("Getting Unit 3");
var unit = GetUnitFromRepo(3);
Console.WriteLine($"Got Unit '{unit.Name}'");
Console.WriteLine("Getting Unit 4");
unit = GetUnitFromRepo(4);
Console.WriteLine($"Got Unit '{unit.Name}'");
Console.WriteLine("Getting Unit 3");
unit = GetUnitFromRepo(3);
Console.WriteLine($"Got Unit '{unit.Name}'");
Console.WriteLine("Getting Unit 4");
unit = GetUnitFromRepo(4);
Console.WriteLine($"Got Unit '{unit.Name}'");
Console.ReadLine();
}
private Unit GetUnitFromRepo(int id)
{
var cache = MemoryCache.Default;
var unit = (Unit) cache[id.ToString()];
if (unit == null)
{
unit = _unitrepo.GetUnitById(id);
cache.Add(id.ToString(), unit, new CacheItemPolicy());
}
return unit;
}
}
internal class Unit
{
public Unit(int id)
{
Id = id;
}
public string Name => Id.ToString();
public int Id { get; }
}
internal class UnitRepo
{
public UnitRepo()
{
Units = new List<Unit>();
for (var i = 0; i < 10; i++)
Units.Add(new Unit(i));
}
public IList<Unit> Units { get; }
public Unit GetUnitById(int id)
{
Console.WriteLine("Gotten from UnitRepo");
return Units.Single(x => x.Id == id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment