I am using System.Runtime.Caching in my Class,but when i use the class to generate different caches for different Master data lists in my application. But these cache objects are malfunctioning in the application, i.e. First list gets the data of the second list from the cache.
public class MemoryCacher : CachingProviderBase,IGlobalCachingProvider
{
protected MemoryCacher()
{
}
public static MemoryCacher Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly MemoryCacher instance = new MemoryCacher();
}
public virtual new void AddItem(string key, object value)
{
base.AddItem(key, value);
}
public virtual object GetItem(string key)
{
return base.GetItem(key,false);//Remove default is true because it's Global Cache!
}
public virtual new object GetItem(string key, bool remove)
{
return base.GetItem(key, remove);
}
}
For my application,using the above class i am creating caches for different List items that are being generated from an API call.
I use Parallel.Invoke() to call the methods parallelly ,
public ActionResult Index()
{
Parallel.Invoke(
() => GetMasterClass1List(),
() => GetMasterClass2List()
);
return View();
}
private List<MasterClass1> GetMasterClass1List()
{
RequestUri = "Home/MyApiMethod1";//For getting the MasterClass1 data
if(MemoryCacher.Instance.GetItem("MasterClass1Cache") != null)
objMasterClass1Result = (List<MasterClass1>)MemoryCacher.Instance.GetItem("MasterClass1Cache");
else
{
HttpResponseMessage response = ConnectAPI(RequestUri);
if (response.IsSuccessStatusCode)
{
objMasterClass1Result = response.Content.ReadAsAsync<List<MasterClass1>>().Result;
MemoryCacher.Instance.AddItem("MasterClass1Cache", objMasterClass1Result );
}
}
return objMasterClass1Result ;
}
private List<MasterClass2> GetMasterClass2List()
{
RequestUri = "Home/MyApiMethod2";//For getting the MasterClass2 data
if (MemoryCacher.Instance.GetItem("MasterClass2Cache") != null)
objMasterClass2Result = (List<MasterClass2>)MemoryCacher.Instance.GetItem("MasterClass2Cache");
else
{
HttpResponseMessage response = ConnectAPI(RequestUri);
if (response.IsSuccessStatusCode)
{
objMasterClass2Result = response.Content.ReadAsAsync<List<MasterClass2>>().Result;
MemoryCacher.Instance.AddItem("MasterClass2Cache", objMasterClass2Result );
}
}
return objMasterClass2Result ;
}
So here, objMasterClass1Result has the data related to objMasterClass2Result.
This issue occurs only when i use Parallel.invoke , but if use just call the methods one after the other the caching works absolutely fine.
Can some one tell me why this might be happening?