Created
August 29, 2017 15:23
-
-
Save sebingel/561faff165180f4e1cba39d88718d304 to your computer and use it in GitHub Desktop.
Short example of MemoryCache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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