If you ever need a in-memory cache to be maintained, then use MemoryCache.
It is an in memory object cache which uses a key to identify the item in the cache. From the first look it sounds like a dictionary.
Look at the sample code below :
However memory cache provides some advantages.
The MemoryCache has an eviction strategy, so that it can discard objects that are no longer needed or for that you do not have enough memory anymore.
MemoryCache is thread-safe and has methods such as AddOrGetExisting. Doing things yourself in a dictionary or concurrent dictionary is tedious.
It is an in memory object cache which uses a key to identify the item in the cache. From the first look it sounds like a dictionary.
Look at the sample code below :
Code
- using System;
- using System.Runtime.Caching;
- namespace MemoryCacheExample
- {
- class Program
- {
- static void Main()
- {
- var myCache = new MemoryCache("SampleCache");
- var cacheItemPolicy = new CacheItemPolicy();
- myCache.Add(new CacheItem(
- "FOO", new Contact
- {
- Address = new Address
- {
- AddressLine1 = "street 1",
- AddressLine2 = "Area 1",
- City = "Bangalore",
- Country = "India",
- State = "Kar",
- ZipCode = 1243435
- },
- Id = 34,
- Name = "Vikram"
- }), cacheItemPolicy);
- var retrievedItemFromCache = (Contact)myCache.Get("FOO");
- PrintContact(retrievedItemFromCache);
- }
- private static void PrintContact(Contact contact)
- {
- Console.WriteLine("Name : {0}", contact.Name);
- Console.WriteLine("Id : {0}", contact.Id);
- Console.WriteLine("Address1 : {0}", contact.Address.AddressLine1);
- Console.WriteLine("Address2 : {0}", contact.Address.AddressLine2);
- Console.WriteLine("City : {0}", contact.Address.City);
- Console.WriteLine("State : {0}", contact.Address.State);
- Console.WriteLine("Country : {0}", contact.Address.Country);
- }
- }
- public class Contact
- {
- public Contact()
- {
- Address = new Address();
- }
- public int Id { get; set; }
- public string Name { get; set; }
- public Address Address { get; set; }
- }
- public class Address
- {
- public string AddressLine1 { get; set; }
- public string AddressLine2 { get; set; }
- public string City { get; set; }
- public string State { get; set; }
- public string Country { get; set; }
- public long ZipCode { get; set; }
- }
- }
However memory cache provides some advantages.
The MemoryCache has an eviction strategy, so that it can discard objects that are no longer needed or for that you do not have enough memory anymore.
MemoryCache is thread-safe and has methods such as AddOrGetExisting. Doing things yourself in a dictionary or concurrent dictionary is tedious.













